react生命周期 喜欢ヅ旅行 2022-01-31 11:04 284阅读 0赞 # react生命周期 # ### 生命周期图 ### 包含挂载、更新、销毁三个环节 ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0NyaWJ1ZzgwODA_size_16_color_FFFFFF_t_70] ### 生命周期演示 ### 包含两个组件`FaComponents`和`ClassComponent`。为了验证props的变化,所以追踪的是`ClassComponent`的钩子函数。 第一次加载后输出: //首次加载-挂载 constructor componentWillMount render componentsDidMount //点击"加一"按钮更新state addNum shouldComponentUpdate componentWillUpdate render componentDidUpdate //点击destroy componentWillUnmount <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Hello React!</title> <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script> <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script> <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="example"></div> <script type="text/babel"> //class声明组件 class ClassComponent extends React.Component { constructor(props){ super(props) console.log('constructor') this.state = { num:1, } } addNum(){ console.log('addNum') let number = this.state.num number += 1 this.setState({ num:number, }) } componentWillMount(){ console.log('componentWillMount') } componentDidMount(){ console.log('componentsDidMount') } componentWillReceiveProps(){ console.log('componentWillReceiveProps') } shouldComponentUpdate(){ console.log('shouldComponentUpdate') return true } componentWillUpdate(){ console.log('componentWillUpdate') } componentDidUpdate(){ console.log('componentDidUpdate') } componentWillUnmount(){ console.log('componentWillUnmount') } componentDidCatch(){ console.log('componentWillUnmount') } render(){ console.log('render') return ( <div> <h1>{ this.props.v1}</h1> <span>{ this.state.num}</span> <button onClick={ ()=>{ this.addNum()}}>加一</button> </div> ) } } class FaComponents extends React.Component{ constructor(props){ super() this.state={ str:'hello redux', isShow:true, btnTxt:'destroy', } } changeTitle(){ return ()=>{ let temp = this.state.str temp += '123' this.setState({ str:temp, }) } } destroyChild(){ let temp = { 'isShow':!this.state.isShow, 'btnTxt':this.state.isShow?'show':'destroy' } this.setState({ ...temp }) } render(){ return ( <div> <button onClick={ this.changeTitle()}>changeTitle</button> <button onClick={ ()=>{ this.destroyChild()}}>{ this.state.btnTxt}</button> { this.state.isShow ? <ClassComponent v1={ this.state.str} /> : null} </div> ) } } ReactDOM.render( <div> <FaComponents></FaComponents> </div>, document.getElementById('example') ); </script> </body> </html> [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0NyaWJ1ZzgwODA_size_16_color_FFFFFF_t_70]: /images/20220131/b6e065f1337a464f86816336c51efce4.png
还没有评论,来说两句吧...