// Father.js
class Father extends Component {
constructor(props){
super(props);
this.state = {
reset: 'unreset',
father: {
name:'father'
}
};
this.resetData = this.resetData.bind(this);
}
resetData () {
this.setState({
father: {
name:'father 2'
}
});
}
render() {
return (
<div className="App">
<Child father={this.state.father} resetData={this.resetData}/>
</div>
);
}
}
export default Father;
// Child.js
class Child extends Component {
constructor(props){
super(props);
const {father} = this.props;
this.state = {
isChange: 'unChange',
father: father,
};
this.change = this.change.bind(this);
}
change () {
this.setState({
isChange: 'change',
});
setTimeout(this.props.resetData,2000);
}
render() {
return (
<div className="App" onClick={this.change}>
{this.state.isChange}
<br/>
{this.props.father.name}
<br/>
{this.state.father.name}
</div>
);
}
}
export default Child;
为什么点击之后只有一个改变?
点击前
点击后
1.两个
father
变量都是引用类型,但是父组件的resetData
直接改变了father
的地址,子组件引用的仍然是旧的father
2.你只在构造函数内把
props.father
的值赋给了state.father
,后面随着props.father
的改变,state.father
并不会主动响应,原因见上一点3.解决方法有两种:
1)全都用
props.father
2)添加
componentWillReceiveProps
函数: