标签:style str mamicode ati code dataset math oct extend
推荐阅读:https://zh-hans.reactjs.org/docs/react-component.html#mounting
生命周期图谱
http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
1. 挂载时
2. 更新时
3. 卸载时
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>
标签:style str mamicode ati code dataset math oct extend
原文地址:https://www.cnblogs.com/amiezhang/p/11623446.html