React 组件生命周期

2016-08-12  本文已影响0人  wmtcore

实例化

getDefaultProps 只会被调用一次

getInitalState 每个实例调用一次

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

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

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

var datasource=[];

var MyComponent=React.creatClass({
    render:function(){
        return <input />;
    },
    componentDidMount: function(){
        $(this.getDOMNOde()).autocomplete({
            sources: datasource
        })
    }
})

存在期

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

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中添加的任务都要在此撤销,如定时器、事件监听

上一篇 下一篇

猜你喜欢

热点阅读