一,常用的生命周期方法
1,render()
必须实现的方法,里面应该是纯函数,即在不修改state的前提下,每次渲染都返回相同的结果,并且不会直接与浏览器交互。
PS.如果shouldComponentUpdate()返回false,则不调用render()
2,constructor(props)
如果不初始化state或不进行方法绑定,则不需要为react组件实现构造函数。必须在其他语句前面调用super(props)。constructor函数中不要修改state,只用于赋state初始值。
3,componentDidMount()
组件挂载后(插入DOM)中立即调用。(一般如果通过接口请求获取数据放在这里)。这里可以触发额外渲染,渲染发生在显示之前,所以如果渲染设计DOM大小或者位置等会影响显示的操作可以放在这里。
4,componentDidUpdate()
组件更新后调用。第一次加载不调用,可以在这个部分更改状态,但是必须提前包裹在一个条件语句里,否则会死循环。
5,componentWillUnmount()
组件销毁之前调用,可以用来清楚定时器,解绑dom事件,清楚网路状态等。(eg:clearTimeout(this.timer) ||||| window.onScroll = null |||||| this.setState = (state,callback) => {
return
}
二,生命周期
当组件实例被创建并插入DOM中,其生命周期调用顺序如下:
挂载:
constructor
static getDerivedStateFromProps
render
componentDidMount
更新:
static getDerivedStateFromProps
shouldComponentUpdate
render
getSnapshotBeforeUpdate
componentDidUpdate
卸载
componentWillUnmount
错误处理
static getDerivedStateFromError()
componentDidCatch()
react生命周期
最新推荐文章于 2023-01-11 13:53:10 发布