react 组件生命周期
推荐阅读:https://zh-hans.reactjs.org/docs/react-component.html#mounting
生命周期图谱
http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
1. 挂载时
- constructor 构造器
- static getDerivedStateFromProp(props, state) return object 或者 null,用于改写state
- render return jsx 或者 React.createElement(....) 渲染组件的UI
- componentDidMount 组件挂载完成,一般在此时发起请求,获取数据
2. 更新时
- static getDerivedStateFromProp(props, state)
- shouldComponentUpdate(nextProps, nextState) return boolean,如果是false,则不更新,true则更新
- render
- getSnapshotBeforeUpdate(prevProps, prevState) 在更新dom之前获取一些dom的状态,例如scrollTop
- componentDidUpdate(prevProps) 组件更新完成,一般用于需要对比前后prop的时候
3. 卸载时
- componentWillUnmount 组件即将销毁,一般用于清除timer、中止网络请求等等
demo:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>test react component lifecycle</title> </head> <body> <div id="app" data-name="啊咩"></div> <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> <script type="text/babel"> const e = React.createElement; class MyComponent extends React.Component { rootNode = null; constructor(props) { super(props); this.state = {name: props.name} debugger console.log('constructor'); } static getDerivedStateFromProps(props, state){ debugger console.log('state from props'); return {...state, extraInfo: new Date().toLocaleString()} } shouldComponentUpdate(nextProps, nextState) { debugger console.log('should component update'); return nextState.name > 0.2 } render() { debugger // this.state ---> {extraInfo: "2020/10/27 上午9:25:18", name: "啊咩"} console.log('render'); return (<div> <button ref = { node => (this.rootNode = node)} onClick={() => {this.setState({name: Math.random()})}}> {this.state.name} </button> </div>) } componentDidMount() { debugger console.log('did mount'); } getSnapshotBeforeUpdate(prevProps, prevState) { debugger console.log('get snapshot before update'); return 123 } componentDidUpdate(prevProps, prevState, snapshotReturn) { // snapshotReturn ---> 123 debugger console.log('did update'); } componentWillUnmount() { debugger console.log('will unmount'); } } const dom = document.getElementById('app') ReactDOM.render( e(MyComponent, {name: dom.dataset.name, num: 2333}), dom ) </script> </body> </html>