如果你熟悉avalon,使用过 data-include-rendered 和 data-include-loaded 等回调方法,那么你会很好地理解React组件的各个生命周期。
说白了其实就是React组件状态变化前后的时间点,我们可以利用生命周期的接口在相应的时间点做回调操作。
React的官方文档提及了如下几个组件的生命周期:
Mounting/组件挂载相关:
componentWillMount
componentDidMount
componentDidMount
Updating/组件更新相关:
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
Unmounting/组件移除相关:
componentWillUnmount
下面我们将通过一些实例来理解它们。顺便说下本文的示例都可以在我的github上下载到。
一. Mounting/组件挂载相关
componentWillMount
在组件挂载之前执行操作,但仅执行一次,即使多次重复渲染该组件,或者改变了组件的state:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>componentWillMount</title> <script src="react.js"></script> <script src="JSXTransformer.js"></script> </head> <body> <div id="a">123</div> <script type="text/jsx"> var i = 0; var Component1 = React.createClass({ componentWillMount: function(){ console.log(i++) }, getInitialState: function() { return { isClick: !1 } }, clickCb: function() { this.setState({ isClick : !0 }) }, render: function() { return <div onClick={this.clickCb}>isClick:{this.state.isClick? 'yes' : 'nope'}</div> } }); var div = document.getElementById('a'); React.render( <Component1 />,div ); React.render( <Component1 />,div ); </script> </body> </html>
如果希望该回调能执行多次,可以使用 React.unmountComponentAtNode(该方法我们下篇文章再介绍)移除掉已有的组件,然后再重新 render:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>componentWillMount</title> <script src="react.js"></script> <script src="JSXTransformer.js"></script> </head> <body> <div id="a">123</div> <script type="text/jsx"> var i = 0; var Component1 = React.createClass({ componentWillMount: function(){ console.log(i++) }, getInitialState: function() { return { isClick: !1 } }, clickCb: function() { this.setState({ isClick : !0 }) }, render: function() { return <div onClick={this.clickCb}>isClick:{this.state.isClick? 'yes' : 'nope'}</div> } }); var div = document.getElementById('a'); React.render( <Component1 />,div ); React.unmountComponentAtNode(div); //移除掉已有组件 React.render( <Component1 />,div ); </script> </body> </html>