一、class组件中使用props初始化state,props发生改变,子组件state不会变化
永远不要在 constructor 里使用props初始化state值,要么直接用props渲染,要么使用新的生命周期函数
解决办法(使用getDerivedStateFromProps)
class Child extends Component {
state = { text: '' };
// getDerivedStateFromProps在调用渲染方法之前被调用,无论是在初始装载还是在后续更新中。
// 它应该返回一个对象来更新状态,或者返回null来不更新任何内容。
static getDerivedStateFromProps(props) {
return {
text: props.text
};
}
render() {
return <p>{this.state.text}</p>
}
}
class Parent extends Component {
state = {
name: 'xxx'
}
render() {
return (
<div>
<Child text={this.state.name}/>
<button onClick={() => this.setState({name: 'zzz'})}>change</button>
</div>
)
}
}