React 生命周期
【react 挂载】: 将组件渲染,并构建DOM元素然后插入页面的过程。
1.constructor
在组件创建时执行
2.componentWillMount
在挂载前调用一次。如果在这个函数中调用setState,本次render函数可以看到更新后的state,并且只渲染一次。
3.componentDidMoun
1.组件挂载之后调用一次,这个时候,子组件也都挂载好了。
2.问题:父组件,组件,子组件,三者之间先执行哪个componentDidMoun?
3. 这里可以直接操作dom
4. 可以使用过refs
4.componentWillReceiveProps(nextProps)
组件挂载之后,父组件再次render的时候,组件会调用该方法。nextProps是新传入的props。
5.shouldComponentUpdate(nextProps, nextState)
判断是否需要重新渲染,默认返回true,需要重新render。
1.组件挂载之后,每次调用setState后会调用该方法。
2.组件挂载后,父组件重新渲染,组件会调用该方法。
3.调用this.forceUpdate,不执行该方法。如果父级调用该方法,组件执行正常的周期函数
6.componentWillUpdate(nextProps, nextState)
shouldComponentUpdate返回true或者调用forceUpdate之后,componentWillUpdate会被调用。
7.componentDidUpdate(nextProps, nextState)
除了首次render之后调用componentDidMount,其它render结束之后都是调用componentDidUpdate。
8.componentWillUnmount
组件被卸载的时候调用。一般在componentDidMount里面注册的事件需要在这里删除。
【触发render的4条路径】
1. 首次渲染
2. this.setState
3. 父组件发生改变
4. 调用this.forceUpdate