组件的生命周期
理解
- 组件对象从创建到死亡它会经历特定阶段。
- React组件对象包含一系列勾子函数(生命周期回调函数),在特定的时刻调用。
- 我们在定义组件时,在特定的生命周期回调函数中做特定的工作。
生命周期流程图
- 初始化阶段:HReactDOM.render( )触发—初次渲染
1. constructor()
2. componentWillMount()
3. render()
4. componentDidMount() - 更新阶段:由组件内部this.setSate()或父组件render触发
- shouldcomponentUpdate()
- componentwillUpdate()
- render()
- componentDidUpdate()
- 卸载组件:由ReactDOM. unmountComponentAtNode()触发
- componentwillUnmount()
重要的勾子
- render:初始化渲染或者更新渲染调用
- componentDidMount:开启监听,发送ajax请求。
- componentWillUnmount:做一些收尾工作,如:清理定时器
即将废弃的勾子
- componentWillMount
- componentWillReceiveProps
- componentWillUpdate
现在使用会出现警告,下一个大版本需要机上UNSAFE_前缀才能使用,以后可能会被彻底废弃,不建议使用。