React生命周期介绍 发表于 2017-04-29 | 更新于 2017-04-29 | 阅读次数 1 react各个生命周期的介绍 React 生命周期如下:12345678910111213141516171819componentWillMount:1、渲染前调用render:2、渲染componentDidMount:3、第一次渲染完调用,此时可获取domcomponentWillReceiveProps:4、接收到一个新的props时调用shouldComponentUpdate:5、接收props或state时判断是否该updatecomponentWillUpdate:6、接收到props或state时开始更新render:7、rendercomponentDidUpdate:8、组件更新完毕componentWillUnmount:~移除组件时调用 生命周期实例demo123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <script src="http://static.runoob.com/assets/react/react-0.14.7/build/react.min.js"></script> <script src="http://static.runoob.com/assets/react/react-0.14.7/build/react-dom.min.js"></script> <script src="http://static.runoob.com/assets/react/browser.min.js"></script></head><body> <div id="example"></div> <script type="text/babel"> var Button = React.createClass({ getInitialState: function () { return { data: 0 }; }, // 自定义事件 setNewNumber: function () { // this.setState({data: this.state.data + 1}) // this.setState(function (state) { // return {data: state.data + 1} // }) this.setState(function (state) { state.data++ }) }, render: function () { return ( <div> <button onClick = { this.setNewNumber }>INCREMENT</button> <Content myNumber = { this.state.data } /> </div> ); } }); var Content = React.createClass({ // 1、渲染前调用 componentWillMount:function () { console.log('Component Will Mount!') }, // 3、第一次渲染完调用,此时可获取dom componentDidMount: function () { console.log('Component Did Mount!') }, // 4、接收到一个新的props时调用 componentWillReceiveProps: function () { console.log('Component Will Receive Props!') }, // 5、接收props或state时判断是否该update shouldComponentUpdate: function (nextProps, nextState) { console.log('Should Component Update') return true; }, // 6、接收到props或state时开始更新 componentWillUpdate: function () { console.log('Component Will Update!') }, // 7、再次render // 8、组件更新完毕 componentDidUpdate: function () { console.log('Component Did Update!') }, // ~移除组件时调用 componentWillUnmount: function () { console.log('Component Will UnMount!') }, // 2、渲染 render: function () { console.log('Render') return ( <div> <h3>{this.props.myNumber}</h3> </div> ); } // 正确的顺序: // 1、componentWillMount // 2、render // 3、componentDidMount // // 4、componentWillReceiveProps // 5、shouldComponentUpdate // 6、componentWillUpdate // 7、render // 8、componentDidUpdate // // 9、componentWillReceiveProps // 10、shouldComponentUpdate // 11、componentWillUpdate // 12、render // 13、componentDidUpdate // // ~componentWillUnmount }) ReactDOM.render( <Button />, document.getElementById('example') ); </script></body></html> 本文作者: Pimi Chen 本文链接: http://pimichen.com/blog/react/react生命周期.html 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!