先上一张经典的React生命周期的图,有了它,对于我这种懒人来说,省去了记忆的过程。
![](https://img.haomeiwen.com/i9177364/b419c99d3f2b85f2.jpg)
react中的state改变时,都会调用componentWillUpdate,render,componentDidUpdate,这三个方法来重新渲染DOM(shouldComponentUpdate这个方法默认返回true)。
但是如果视图中涉及到一些方法是在 componentDidMount 中执行的话,它只是在组件创建初始时执行一次,state中的状态值与 componentDidMount 中的方法有关联的时候,state的改变并不能使得此时调用方法中的状态改变。
所以,可以通过componentWillReceiveProps这个方法来解决,任何时刻组件的props都可以通过父辈组件来更改,出现这种情况时,componentWillReceiveProps方法会被调用,你将获得更改props方法及跟他关心state的机会。
componentWillReceiveProps(nextProps){
this.setState({
},()=>{
//这里再次执行componentDidMount中的方法时候传入改变后的state
})
}
对了,这种情况的前提是在初始化state的时候,state的是通过props中的值来设置的。
网友评论