- 挂载时
- 更新时
-
- setState触发更新、父组件重新渲染时触发更新
- forceUpdate触发更新
- 卸载时
react(v17.0.2)的生命周期图谱如下。
相较于16版本,17版本生命周期函数有如下变化:
componentWillMount()
componentWillUpdate()
componentWillReceiveProps()
+getDerivedStateFromProps(props,state)
+getSnapshotBeforeUpdate(prevProps,prevState)
虽然UNSAFE_componentWillMount、UNSAFE_componentWillUpdate、UNSAFE_componentWillReceiveProps当前依然可用,但在react未来的版本中可能被移除,所以尽量避免使用。更多可以访问如下链接:
https://react.docschina.org/docs/react-component.html。
https://react.docschina.org/blog/2018/03/27/update-on-async-rendering.html。
挂载时
组件挂载时,会依次调用如下生命周期函数:
constructor(props)
static getDerivedStateFromProps(props)
render()
componentDidMount()
其中,getDerivedStateFromProps
必须用static
修饰,它是类上的方法。且必须返回null
或者状态对象(State Obect)。
getDerivedStateFromProps
在实际开发中几乎不用,仅适用于state唯一取决于props的场景。
更新时
setState触发更新、父组件重新渲染时触发更新
setState、父组件重新渲染触发更新时,会依次调用如下生命周期函数:
1、static getDerivedStateFromProps()
2、shouldComponentUpdate(nextProps,nextState)
3、render()
4、getSnapshotBeforeUpdate(prevProps,prevState)
5、componentDidUpdate(prevProps,prevState,snapshot)
其中,getSnapshotBeforeUpdate(prevProps,prevState)必须返回null或任意快照值(Snapshot Value,undefined除外)。返回的快照值将作为componentDidUpdate的第三个形参。
forceUpdate触发更新
forceUpdate触发更新,会依次调用以下生命周期函数:
static getDerivedStateFromProps()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
卸载时
组件卸载时,会调用生命周期函数:
componentWillUnmount()
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>test</title><script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script><script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head><body><div id="app"></div><script type="text/babel">class Count extends React.Component{constructor(props){console.log("Count---constructor");super(props);this.state = {count:0}}componentDidMount(){console.log("Count---componentDidMount");}static getDerivedStateFromProps(){console.log("Count---getDerivedStateFromProps");return null;}shouldComponentUpdate(){console.log("Count---shouldComponentUpdate");return true;}getSnapshotBeforeUpdate(){console.log("Count---getSnapshotBeforeUpdate");return null;}componentDidUpdate(){console.log("Count---componentDidUpdate");}componentWillUnmount(){console.log("Count---componentWillUnmount");}death = () => {ReactDOM.unmountComponentAtNode(document.getElementById("app"));}add = () => {const {count} = this.state;this.setState({count:count+1})}force = () => {this.forceUpdate();}render(){console.log("Count---render");const {count} = this.state;const {add,death,force} = this;return (<div><h2>当前值为:{count}</h2><button onClick={add}>点我加1</button> <button onClick={force}>强制更新</button> <button onClick={death}>卸载组件</button></div>)}}ReactDOM.render(<Count/>,document.getElementById("app"));</script>
</body></html>