您的位置:首页 > Web前端 > React

react组件生命周期钩子函数

2018-10-31 19:40 776 查看

挂载期

constructor 数据接收 实现继承super(props)
componentWillMount 数据挂载之前 在constructor执行之后 可以操作数据 不可以操作dom
componentDidMount 数据挂载之后 可以操作数据和dom 适用于数据请求
render 渲染组件 和 html 标签

getDefaultProps
getInitialState
componentWillMount
render
componentDidMount

更新期

shouldComponentUpdate 检测组件内的变化 可以用作页面性能的优化(默认值为true)
componentReceiveProps 接收组件传入输入数据
componentWillUpdate 组件更新之前调用
componentDidUpdate 组件更新之后调用
render 组件更新之后渲染组件

componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate

销毁期

componentWillUnmount 组件销毁时调用 可以做一些内存的优化 (全局变量,闭包,计时器,事件)

生命周期 调用次数 能否使用 setSate()
getDefaultProps 1(全局调用一次)
getInitialState 1
componentWillMount 1
render >=1
componentDidMount 1
componentWillReceiveProps >=0
shouldComponentUpdate >=0
componentWillUpdate >=0
componentDidUpdate >=0
componentWillUnmount 1

组件生命周期的三个状态:

Mounting 已插入真实 DOM
Updating 正在被重新渲染
Unmounting 已移出真实 DOM

生命周期的方法:

方法 作用
componentWillMount 在渲染前调用,在客户端也在服务端
componentDidMount 在第一次渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()来进行访问
componentWillReceiveProps 在组件接收到一个新的 prop (更新后)时被调用。这个方法在初始化render时不会被调用
shouldComponentUpdate 返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用
componentWillUpdate 在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用
componentDidUpdate 在组件完成更新后立即调用。在初始化时不会被调用
componentWillUnmount 组件销毁期的周期函数 在组件从 DOM 中移除之前立刻被调用
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: