這個也是在實際項目中遇到的坑,畢竟我比較年輕~_~
先來個父組件的代碼:
// 父組件
class Car extends Component {
constructor(props){
super(props);
this.state = {
smallCar: {
color:'red'
}
};
this.resetCar = this.resetCar.bind(this);
}
resetCar () {
this.setState({
smallCar: {
color:'pink'
}
});
}
render() {
return (
<div className="App">
<SmallCar smallCar={this.state.smallCar} resetCar={this.resetCar}/>
</div>
);
}
}
export default Car;
再來個子組件:
// 子組件
class SmallCar extends Component {
constructor(props){
super(props);
const { smallCar } = this.props;
this.state = {
isChange: 'unchange',
smallCar:smallCar,
};
this.change = this.change.bind(this);
}
change () {
this.setState({
isChange: 'change',
});
setTimeout(this.props.resetCar,2000);
}
render() {
return (
<div className="App" onClick={this.change}>
{this.state.isChange}
<br/>
{this.props.smallCar.name}
<br/>
{this.state.smallCar.name}
</div>
);
}
}
export default SmallCar;
兩個smallCar
變量都是引用類型,但是父組件的resetCar
直接改變了smallCar
的地址,子組件引用的仍然是舊的smallCar。
你只在構造函數內把props.smallCar
的值賦給了state.smallCar
,後面隨着props.smallCar
的改變,state.smallCar
並不會跟着變化。
1)全都用props.smallCar,這個就不展開了
2) 添加componentWillReceiveProps
函數:
// 子組件
class SmallCar extends Component {
constructor(props){
super(props);
const { smallCar } = this.props;
this.state = {
isChange: 'unchange',
smallCar:smallCar,
};
this.change = this.change.bind(this);
}
// 加上我
componentWillReceiveProps = (nextProps) => {
this.setState({
smallCar: nextProps.smallCar
})
}
change () {
this.setState({
isChange: 'change',
});
setTimeout(this.props.resetCar,2000);
}
render() {
return (
<div className="App" onClick={this.change}>
{this.state.isChange}
<br/>
{this.props.smallCar.name}
<br/>
{this.state.smallCar.name}
</div>
);
}
}
export default SmallCar;