1.子组件中尽量直接使用props的数据 具体原因看https://blog.csdn.net/nnxxyy1111/article/details/80832525
2.如果必须保存在state中可以在componentWillReciveProps这个生命周期中更新
constructor(props) {
super(props);
this.state = {
num: 1,
propsData: props.data
}
}
componentWillReceiveProps(nextProps) {
console.log("componentWillReceiveProps===>", nextProps.data)
this.setState({
propsData: nextProps.data
})
}
3.可以使用新的生命周期getDerviedStateFromProps
static getDerivedStateFromProps(nextProps, prevState) {
const {type} = nextProps;
// 当传入的type发生变化的时候,更新state
if (type !== prevState.type) {
return {
type,
};
}
// 否则,对于state不进行任何操作
return null;
}
react 生命周期理解https://www.cnblogs.com/gdsblog/p/7348375.html