React组件包含一系列生命周期钩子函数,会在特定的时刻调用。
在定义组件时,可以在特定的生命周期回调函数中做特定的事。
旧生命周期
1. 初始化阶段:由ReactDOM.render()触发 ---- 初次渲染
constructor()
componentWillMount()
render()
componentDidMount() 【常用 初始化】开启定时器、发送网络请求、订阅消息
2. 更新阶段:由组件内部this.setState()或父组件重新render触发
componentWIllReceiveProps() 组件将要接收到props时调用【但第一次接收时是不会调用的】
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()
3. 卸载组件:由ReactDOM.unmountComponentAtNode()触发
componentWillUnmount() 【常用 收尾】关闭定时器、取消订阅消息
新生命周期
与旧的生命周期相比,即将废弃三个生命周期钩子
【componentWillMount、componentWIllReceiveProps、componentWillUpdate】
增加了两个新的生命周期钩子
【getDerivedStateFromProps、getSnapshotBeforeUpdate】
1. 初始化阶段:由ReactDOM.render()触发 ---- 初次渲染
constructor()
getDerivedStateFromProps()【需要返回一个对象,来更新state】
render()
componentDidMount()
2. 更新阶段:由组件内部this.setState()或父组件重新render触发
getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()【在最近一次渲染输出之前调用。它使得组件能在发生更改之前从 DOM 中捕获一些信息(例如,滚动位置)】
componentDidUpdate()
3. 卸载组件:由ReactDOM.unmountComponentAtNode()触发
componentWillUnmount()