脚本宝典收集整理的这篇文章主要介绍了React16 生命周期理解,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
完整生命周期
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 & 生命周期 && 性能优化 章节
以上是脚本宝典为你收集整理的React16 生命周期理解全部内容,希望文章能够帮你解决React16 生命周期理解所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。