Component initial
1. constructor() 会在装配之前调用,构造函数是初始化状态的合适位置
可以基于属性来初始化状态,这样有效的分离属性并根据初始属性设置状态
constructor(props) {
super(props);
this.state = {
color: props.initialColor
};
}
2. UNSAFE_componentWillMount()
在这个方法里同步的设置状态不会触发重渲,建议使用
constructor()
来初始化状态避免在该方法中引入任何的副作用或者订阅,这是唯一的会在服务器渲染掉的生命周期的钩子函数
3. render()
render()
函数应该是纯函数,意味着其不应该改变组件的状态,保持render()
方法的纯净使得组件更容易思考
若shouldComponentsUpdate()
返回false
,render()
将不会被调用
4. componentDidMount()
若要从远端加载数据,这是一个适合实现网络请求的地方,该方法设置状态将会触发重渲
state Changes
5. shouldComponentUpdate(nextProps, nextState)
默认返回true
6. UNSAFE_componentWillUpdate(nextProps, nextState)
不能在这里调用
this.setState()
,若你需要更新状态响应属性的调整,使用componentWillMount()
代替。
7. componentDidUpdate(nextProps, nextState)
Props Changes
8. UNSAFE_componentWillReceiveProps(nextProps)
componentWillReceiveProps()
在装配了的组件接收到新属性前调用。若你需要更新状态响应属性改变(例如,重置它),你可能需对比this.props
和nextProps
并在该方法中使用this.setState()
处理状态改变。
Unmounting
9. componentWillUnmount()
componentWillUnmount()
在组件被卸载和销毁之前立刻调用。可以在该方法里处理任何必要的清理工作,例如解绑定时器,取消网络请求,清理任何在componentDidMount环节创建的DOM元素。