React 组件就是一个状态机,它接受两个输入参数: this.props 和 this.state,返回一个虚拟DOM。
React组件的生命周期分几个阶段,每个阶段会有若干个回调函数可以响应不同的时刻。
1.创建阶段
getDefaultProps:处理props的默认值 在React.createClass调用
2.实例化阶段
getInitialState: 获取 this.state 的默认值
componentWillMount: 在render之前调用此方法,在render之前需要做的事情就在这里处理
render: 渲染并返回一个虚拟DOM
componentDidMount: 在render之后,react会使用render返回的虚拟DOM来创建真实DOM,完成之后调用此方法。
state:组件的属性,主要是用来存储组件自身需要的数据,每次数据的更新都是通过修改state属性的值,ReactJS内部会监听state属性的变化,一旦发生变化的话,就会主动触发组件的render方法来更新虚拟DOM结构
其中有几个点需要注意:
1,this.state 只存储原始数据,不要存储计算后的数据
比如 this.state.time = 1433245642536,那么就不要再存一个 this.state.timeString = ‘2015-06-02 19:47:22’ 因为这个是由 time 计算出来的,其实他不是一种state,他只是 this.state.time 的一种展示方式而已。
这个应该放在render中计算出来:
<span>time: {this.formatTime(this.state.time)}</span>
2,componentWillMount 用来处理render之前的逻辑,不要在render中处理业务逻辑。
render就是一个模板的作用,他只处理和展示相关的逻辑,比如格式化时间这样的,如果有业务逻辑,那么要放在 componentWillMount 中执行。
所以render中一定不会出现改变 state 之类的操作。
3,render返回的是虚拟DOM
所谓虚拟DOM,其实就是 React.DOM.div 之类的实例,他就是一个JS对象。render方法完成之后,真实的DOM并不存在。
4,componentDidMount 中处理和真实DOM相关的逻辑
这时候真实的DOM已经渲染出来,可以通过 this.getDOMNode() 方法来使用了。典型的场景就是可以在这里调用jquery插件。
3.更新阶段
主要发生在用户操作之后或父组件有更新的时候,此时会根据用户的操作行为进行相应的页面结构的调整
componentWillReceiveProps、shouldComponentUpdate、componentWillUpdate、render、componentDidUpdate
componentWillRecieveProps: 父组件或者通过组件的实例调用 setProps 改变当前组件的 props 时调用。
shouldComponentUpdate: 是否需要更新,慎用
componentWillUpdate: 调用 render方之前
render:
componentDidUpdate: 真实DOM已经完成更新。
4.销毁阶段
销毁时被调用,通常做一些取消事件绑定、移除虚拟DOM中对应的组件数据结构、销毁一些无效的定时器等工作
componentWillUnmount
举例说明组件的生命周期
下面这个例子演示了ReactJs的生命周期:
var NotesList = React.createClass({
getDefaultProps: function() {
console.log("getDefaultProps");
return {};
},
getInitialState: function() {
console.log("geyInitialState");
return {};
},
componentWillMount: function() {
console.log("componentWillMount");
},
render: function() {
console.log("render");
return (
<div>hello <strong>{this.props.name}</strong></div>
);
},
componentDidMount: function() {
console.log("componentDidMount");
},
componentWillRecieveProps: function() {
console.log("componentWillRecieveProps");
},
componentWillUpdate: function() {
console.log("componentWillUpdate");
},
componentDidUpdate: function() {
console.log("componentDidUpdate");
},
});
var list1 = React.render(
<NotesList name='aaa'></NotesList>,
document.getElementById("div1")
);
var list2 = React.render(
<NotesList name='bbb'></NotesList>,
document.getElementById("div2")
);
执行这一段代码,实际上做了三件事:
创建了一个类 NodesList
创建了一个对象 list1
创建了一个对象 list2
那么在创建类的时候,输出:
getDefaultProps
在创建list1和 list2的时候都会输出:
geyInitialState
componentWillMount
render
componentDidMount
于是执行这段代码,最终输出的就是:
getDefaultProps
geyInitialState
componentWillMount
render
componentDidMount
geyInitialState
componentWillMount
render
componentDidMount
此时已经存在一个类 NodesList 和 两个对象 list1 & list2
然后我们执行 list1.setProps({name: “ccc”})。那么输出如下:
componentWillUpdate
render
componentDidUpdate
可以发现页面上的 hello aaa 已经变成了 hello ccc
本文详细介绍了React组件的生命周期,包括创建、实例化、更新和销毁四个阶段,并通过具体示例展示了各阶段的主要方法及其调用顺序。
927

被折叠的 条评论
为什么被折叠?



