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,便不再进行组件更新了,提升页面性能
例子
这个例子让你更好的理解几个生命周期的作用 Github地址在这里

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理