完整生命周期
constructor(props) // 初始化参数
componentWillMount()
render() // 第一次渲染
componentDidMount()
当父组件向子组件传入props发生改变后,依次调用
componentWillReceiveProps(nextProps)
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate()
render() //子组件更新渲染
componentDidUpdate()
当组件自身state发生变化后
componentWillUpdate()
render() //组件再次更新渲染
componentDidUpdate()
当组件卸载
componentWillUnmount()
生命周期详解
componentDidMount() 此处请求接口数据
componentWillReceiveProps(nextProps) 子组件得到新props时触发,做用是在子组件再次渲染前,更新子组件自身的state,以后会触发shouldComponentUpdate()
shouldComponentUpdate(nextProps, nextState) 接受的props发生变化或者自身state变化都会触发该生命周期,在今生命周期能够作一些渲染的优化,默认返回true,就是默认须要更新组件,从新渲染,nextProps nextState 都是新state 新props,this.props this.state 表示旧的props state,根据需求作优化,好比在某些状况下返回false,便再也不进行组件更新了,提高页面性能
static getDerivedStateFormProps(nextProps, prevState)
替代 componentWillReceiveProps 返回的结果会送给setState 若是什么都不改变就返回null
static 声明静态函数,没法访问this,也就是一个纯函数,输出彻底由输入决定
除了shouldComponentUpdate以外,render前的全部生命周期都被替代
返回新的state,从新进行setSate后,react会去控制再也不进行新的更新
AJAX请求在依旧在componentDidMount 中进行,只有在一些特定状况下实用 (此处还未深刻了解
貌似用的场景不多
eg:
static getDerivedStateFromProps(nextProps, prevState) {
console.log(nextProps); // 新传入的props
console.log(prevState); // 旧的state
//console.log(this.props);
return {
value: nextProps.value
}
}
例子
这个例子让你更好的理解几个生命周期的做用
Github地址在这里


参考react官方文档
State & 生命周期 &&
性能优化 章节