关于react生命周期

react生命周期有三种状态1初始化2更新3销毁

初始化阶段

1 getDefaultProps();

设置组件的默认属性,也可以defaultProps:{}设置

2 getInitialState();

ES6中直接继承Component类,使用this.state={},此时可以访问this.props

3 componentWillMount();

渲染之前调用,既在客户端也在服务端

4 render();

react最重要的步骤,创建虚拟Dom渲染UI,此时不能修改state;

5 componentDidMount();

 首次渲染之后调用,该阶段调用ajax请求,防止异步操作阻塞UI。官方推荐此时请求数据

6 componentWillReceiveProps(nextProps);

if (this.props.sectionList !== nextProps.sectionList && this.props.leftkeycode !== nextProps.leftkeycode)

 初始化时不调用,组件接受新的props时调用,只有存在props更新才调用该事件钩子,此时setState是安全的,

7 shouldComponentUpdate(nextProps,nextState);

react性能优化非常重要的一环,组件接收新的props,state时调用,比较之前的state和props是否相同,相同返回false阻止更新,此钩子节省大量性能。

8 componentWillUpdate();

组件初始化时不调用,组件将更新时进行调用,此时可以修改state,但可能出现循环调用,耗尽内存

9 componentDidUpdate();

组件初始化时不调用,组件更新完成时调用。调用setState,可能会造成死循环,所以要限制好setState的条件

10 componentWillUnmount(); 

组件将要卸载时调用,一些事件监听和定时器需要在此时清除

11 componentDidCatch(); 

用来捕获组件的错误,react16新添加的

 

以下两种情况

1  属性props改变

  先  componentWillReceiveProps  然后    shouldComponentUpdate

2  状态state改变

  先  shouldComponentUpdate   决定要不要   componentWillUpdate

 

log打印顺序   1外层   2constructor   3componentWillMount

4render   5conponentDidMount   6异步请求 

posted @ 2018-08-06 16:00  shuaibijian  阅读(183)  评论(0)    收藏  举报