React Native生命周期

方法名

作用


constructor

构造函数,初始化需要的state

1次

componentWillMount

控件渲染前触发

1次

rander

渲染控件的方法

多次

componentDidMount

控件渲染后触发

1次

componentWillReceiveProps

组件接收到新的props时被调用

多次

shouldComponentUpdate

当组件接收到新的props和state时被调用

多次

componentWillUpdate

props或者state改变,并且此前的shouldComponentUpdate方法返回为 true会调用该方法

多次

componentDidUpdate

组件重新渲染完成后会调用此方法

多次

componentWillUnmount

组件卸载和销毁之前被调用

1次

1,执行顺

初次加载:依次触发了父控件的构造函数,componentwillMount,render,子控件的构造函数,子控件的componentwillMount,render,componentwillMount,最后才是父控件的componentwillMount。初次的渲染周期是从外向内逐步渲染,内部完成后才算整体结束。

UI更新:一圈一摸一样的流程完成刷新.

卸载:也是从外向内触发,最后才是父控件的componentwillUnmount。


2,几点建议:

constructor()方法里初始化state 

componentWillMount()可在方法里对state进行最后的修改,在初始化render之前执行,如果在这个方法内调用setStaterender()知道state发生变化,并且只执行一次;

componentDidMount()方法里跑网/耗时操作 ,在初始化render之后只执行一次,在这个方法内,可以访问任何组件,componentDidMount()方法中的子组件componentDidMount()方法在父组件之前执行;

componentWillReceivePropsprops发生变化时执行,初始化render时不执行,在这个回调函数里面,你可以根据属性的变化,通过调用this.setState()来更新你的组件状态,旧的属性还是可以通过this.props来获取,这里调用更新状态是安全的,并不会触发额外的render调用

componentWillUnmount当组件要被从界面上移除的时候,就会调用componentWillUnmount(),在这个函数中,可以做一些组件相关的清理工作,例如取消计时器、网络请求等;

注意,不要在 constructor 或者 render 里 setState(),這是因为 constructor 已含 this.state={} ,而 render 里 setState 会造成setState -> render -> setState -> render,能做的setState,只要是render前,就放在componentWillMount,render后,就放在 componentDidMount。这两个 function 是 react lifecycle 中,最常使用的两个。当然啦,还有其它的部分,那就以后研究和推敲它们的使用时机咯!


猜你喜欢

转载自blog.csdn.net/zhangkui0418/article/details/80916237