生命周期:
组件本质上是状态机,输入确定,输出一定确定。
状态发生转换时会触发不同的钩子函数,从而让开发者有机会做出响应
可以用事件的思路来理解状态
初始化对应的回调函数:
getDefaultProps //第一个实例被初始化时调用,只调用一次,实例之间共享引用
getInitialState //初始化每个实例特有的状态
componentWillMount //render之前最后一次修改状态的机会
render //只能访问this.props和this.state,只有一个顶层组件,不允许修改状态和DOM输出
componentDidMount //成功render并渲染完成真实的DOM之后触发,可以修改DOM
$(function(){ var count=0; var style={ color:'red', border:"2px blue solid" }; var HelloWorld=React.createClass({ getDefaultProps:function(){ console.log("init state 1"); return {name:"Tom"}; }, getInitialState:function(){ console.log("init state 2"); return { myCount:count++, ready:true }; }, componentWillMount:function(){ console.log("init state 3"); this.setState({ ready:false }); }, render:function(){ console.log("init state 4"); return <p>hello,{this.props.name||'world'}<br/>{this.state.myCount}<br/> {this.state.ready}<br/></p>; }, componentDidMount:function(){ console.log("init state 5"); $(React.findDOMNode(this)).append("surprise"); } }); React.render(<HelloWorld style={style}></HelloWorld>,document.body); }); </script>
运行中阶段对应的回调函数:
componentWillReceiveProps //父组件修改属性触发,可以修改新属性,修改状态
shouldComponentUpdate //返回false,会组件render调用
componentWillUpdate //不能修改属性和状态
render //跟ready相同
componentDidUpdate //跟ready相同
var style={ color:"blue", border:"1px #00f solid" }; var HelloWorld=React.createClass({ componentWillReceiveProps:function(){ }, shouldComponentUpdate:function(){ return true; }, componentWillUpdate:function(){ }, render:function(){ return <p>Hello {this.props.name||"world"}</p> }, componentDidUpdate:function(){ } }); var HelloUniverse=React.createClass({ getInitialState:function(){ return {name:""}; }, handleChange:function(event){ this.setState({name:event.target.value}); }, render:function(){ return <div> <HelloWorld name={this.state.name}></HelloWorld> <br/> <input type="text" onChange={this.handleChange}/> </div> } }); React.render(<div style={style}><HelloUniverse></HelloUniverse></div>,document.body);
销毁阶段:
componentWillUmount //在删除组件之前进行清理操作,比如计时器和时间监听器
var style={ color:"blue", border:"1px #00f solid" }; var HelloWorld=React.createClass({ render:function(){ return <p>Hello {this.props.name||"world"}</p> }, componentWillUnmount:function(){ console.log("destroy"); } }); var HelloUniverse=React.createClass({ getInitialState:function(){ return {name:""}; }, handleChange:function(event){ if(event.target.value=="123"){ React.unmountComponentAtNode(document.getElementsByTagName("body")[0]); return; } this.setState({name:event.target.value}); }, render:function(){ return <div> <HelloWorld name={this.state.name}></HelloWorld> <br/> <input type="text" onChange={this.handleChange}/> </div> } }); React.render(<div style={style}><HelloUniverse></HelloUniverse></div>,document.body);