react 组件生命周期
Posted amiezhang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 { constructor(props) { super(props); this.state = {name: props.name} console.log(‘constructor‘); } static getDerivedStateFromProps(props, state){ console.log(‘state from props‘); return state } shouldComponentUpdate(nextProps, nextState) { console.log(‘should component update‘); return nextState.name > 0.5 } render() { console.log(‘render‘); return (<div> <button onClick={() => {this.setState({name: Math.random()})}}> {this.state.name} </button> </div>) } componentDidMount() { console.log(‘did mount‘); } getSnapshotBeforeUpdate(prevProps, prevState) { console.log(‘get snapshot before update‘); return null } componentDidUpdate(prevProps) { console.log(‘did update‘); } componentWillUnmount() { console.log(‘will unmount‘); } } const dom = document.getElementById(‘app‘) ReactDOM.render( e(MyComponent, {name: dom.dataset.name}), dom ) </script> </body> </html>
以上是关于react 组件生命周期的主要内容,如果未能解决你的问题,请参考以下文章