React 组件生命周期

实例化

  • 一个实例初次创建

getDefaultProps 只会被调用一次

getInitalState 每个实例调用一次

componentWillMount 首次渲染之前被调用,可以修改state

render 创建虚拟DOM,表示组件输出,必须要有的方法。只能通过this.props和this.state访问数据。返回null、false、任何React组件。只能有一个顶级组件,不能改变组件的状态或者修改DOM的输出。

componentDidMount 在真实的DOM渲染之后,可以通过this.getDOMNode()访问原生DOM,测量渲染的DOM元素高度,运行jQuery

1
2
3
4
5
6
7
8
9
10
11
12
var datasource=[];
var MyComponent=React.creatClass({
render:function(){
return <input />;
},
componentDidMount: function(){
$(this.getDOMNOde()).autocomplete({
sources: datasource
})
}
})

存在期

  • 组件已渲染好,可以和它交互

componentWillReceiveprops 通过父辈组件修改props、state

1
2
3
4
5
6
7
componentWillReceiveProps: function(nextProps) {
if (nextProps.checked !== undefined) {
this.setState({
checked: nextProps.checked
})
}
}

shouldComponentUpdate 优化组件渲染,确实组件是否要渲染新的props、state

componentWillUpdate 在组件接收到新的props或者state渲染之前调用,不可在此更新state、props,要借助componentWillReceiveprops更新state

componentDidUpdate 类似componentDidMount,在此更新已渲染的DOM

销毁&清理期

componentWillUnmountcomponentDidMount中添加的任务都要在此撤销,如定时器、事件监听