这个也是在实际项目中遇到的坑,毕竟我比较年轻~_~
先来个父组件的代码:
// 父组件
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;