React的生命周期从广义上分为三个阶段:挂载、渲染、卸载
Mounting:已插入真实 DOM
Updating:正在被重新渲染
Unmounting:已移出真实 DOM
React的生命周期图:
1. 挂载卸载
constructor()、componentWillMount()、componentDidMount()、componentWillUnmount ()
2. 更新
componentWillReceiveProps (nextProps)
shouldComponentUpdate(nextProps,nextState)
componentWillUpdate (nextProps,nextState)
componentDidUpdate(prevProps,prevState)
render()
3. React新增的生命周期
getDerivedStateFromProps(nextProps, prevState)
getSnapshotBeforeUpdate(prevProps, prevState)
getDerivedStateFromProps(nextProps, prevState)
代替componentWillReceiveProps()
componentWillReceiveProps(nextProps){
let zyy= nextProps.zyy;
this.setState({ a: zyy.a, b: zyy.b}) //更新state
}
static getDerivedStateFromProps(nextProps, prevState) {
const { a,b } = nextProps.zyy;
if(a!== prevState.a){ //传入的props与state不同
return {a:a,b:b} //将传入的props映射到state上
}
return null
}
getSnapshotBeforeUpdate(prevProps, prevState)
代替componentWillUpdate
区别在于:
1、在 React 开启异步渲染模式后,在 render 阶段读取到的 DOM 元素状态并不总是和 commit 阶段相同,这就导致在componentDidUpdate 中使用 componentWillUpdate 中读取到的 DOM 元素状态是不安全的,因为这时的值很有可能已经失效了。
2、getSnapshotBeforeUpdate 会在最终的 render 之前被调用。