问题的起因是我写一个demo的时候,子组件中没有使用this.setState,父组件传给子组件的props也没有变,但是我的子组件还是render了。(除了挂载阶段的render)
让我百思不得其解,于是重新回去梳理了一下React的生命周期,究竟什么可以引发我子组件的render?
子组件的更新分为两种情况
第一种: 父组件render,导致重传props
如果我们在子组件中是直接使用this.props.xxx 那么可以在shouldcomponentUpdata判断props是否变化
如果我们是将父组件的属性转化为自己的state,则可以在componentWillReceiveProps时,用this.setState更新自己state的状态。
第二种:自身调用this.setState
我出现的问题的答案在于,我的父组件render,导致重传props,但是我没有在shouldcomponentUpdata中判断props是否变化,所以就默认为true,所以我的子组件再一次更新
再给大家梳理一下React旧版的生命周期
1.初始化阶段
1.1constructor
做一些初始化工作,比如定义this.state
2.挂载阶段Mount
2.1 componentWillMount
组件挂载前使用,不常用
2.2 render
根据props和state return一个React元素
render方法是一个纯函数
2.3 componentDidMount
组件挂载到Dom后调用且只会调用一次
3.更新阶段Update
这里敲重点!!
问题来了,子组件什么时候会更新?这就是我们最开始抛出来的问题
子组件的更新分为两种情况
第一种: 父组件render,导致重传props
如果我们在子组件中是直接使用this.props.xxx 那么可以在shouldcomponentUpdata判断props是否变化
如果我们是将父组件的属性转化为自己的state,则可以在componentWillReceiveProps时,用this.setState更新自己state的状态。
第二种:自身调用this.setState
3.1 componentWillReceiveProps(nextProps)
此方法只有在第一种情况,props引起的更新才会调用,父组件会传新的props,但不一定是有变化的,所以可以在这里判断是否有变化,我最开始的问题就是,我的父组件重新render了,所以重新传子组件props,但是我没有判断它有没有变化,没有拦截,子组件就会默认render
3.2 shouldComponentUpdata(nextProps,nextState)
返回的是bool值,如果是false则不render
3.3 componentWillUpdate
render前,很少用
3.4 render
3.5 componentDidUpdate
组件更新后被调用,可以操作组件更新的DOM
4.卸载阶段
4.1componentWillUnmount
卸载前调用,可以做一些清理工作
比如清除组件中使用的定时器等
React V16.4之后用
static getDevivedStateFromProps(props,state)
在组件创建和render之前使用,
也就是说取代了:
componentWillMount
componentWillReceiveProps
componentWillUpdate