4、需要根据props更新state时使用
getDerivedStateFromProps(nextProps,prevState)
5、旧props 需要自己存储以便比较
public static getDerivedStateFromProps(nextProps,prevState){
//当新props中的data发生变化时同步更新到state上
if(nextProps. data!==prevState. data){
return {
data:nextProps. data
}
}else {
return null1
}
}
可以在componentDidUpdate监听props或者state的变化例如:
componentDidUpdate(prevProps){
//当id 发生变化时重新获取数据
if (this. props. id!==prevProps. id){
this. fetchData(this. props. id);
}
在componentDidUpdate 使用setState`时必须加条件否则将进入死循环
3、在componentDidMount中进行数据的请求而不是在componentWillMount