好吧,我已经知道一种方法了。然而,我问这个是为了防止我重新发明轮子,因为我是一个非常新的反应。我的印象是,如果父组件通过道具将其状态传递给子组件,而不是在更新父组件的状态时,子组件将在需要时重新渲染。但事实似乎并非如此。我举了个例子,
class Child extends Component {
constructor(props) {
super(props);
this.state = {
number: props.number,
};
}
updateNumber(n) {
this.setState({number: n});
}
render() {
return (<h1>{this.state.number}</h1>);
}
}
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
number: -1,
};
this.child = React.createRef();
setInterval(this.updateState.bind(this), 1000);
}
updateState() {
console.log(this.state);
this.setState({
number: Math.floor((Math.random() * 10) + 1),
});
// this.child.current.updateNumber(this.state.number);
}
render() {
return (
<div>
<Child ref={this.child} number={this.state.number}/>
</div>
);
}
}在本例中,除非我显式定义一个引用并使用它来调用子对象的更新函数(注释部分),否则不会在每次更新父对象的状态时重新呈现该子对象。就这样了吗?你是打算手动更新你的孩子的状态(嘿),还是如果他们的父母的状态作为道具传递给他们,他们应该自动更新(并因此重新渲染)。
发布于 2019-11-23 17:44:41
你的方法是错误的,不要像这样从子状态更新你的父状态,也不要在子状态中保存道具,它们已经随着父状态的更新而更新。
如果你想更新父窗体,子窗体传递道具,像this.when父窗体更新一样,子窗体也会更新。
class Child extends Component {
constructor(props) {
super(props);
}
updateNumber=()=>{// update parent form child. call this function in somewhere in your component. if you want to pass event pass it as second argument
this.props.updateNumber(newUpdatedNumber,event);
}
render() {
return (<h1>{this.props.number}</h1>);
}
}
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
number: -1,
};
this.child = React.createRef();
setInterval(this.updateState.bind(this), 1000);
}
updateState() {
console.log(this.state);
this.setState({
number: Math.floor((Math.random() * 10) + 1),
});
}
//update parent from child
updateParentFromChild=(updatedNumber,event)=>{//catch function from child
this.setState({
number:updatedNumber
});
}
render() {
return (
<div>
<Child ref={this.child} updateNumber={this.updateParentFromChild} number={this.state.number}/>
</div>
);
}
}https://stackoverflow.com/questions/59006178
复制相似问题