【发布时间】:2020-03-19 05:31:56
【问题描述】:
好的,我已经知道一种方法可以做到这一点。但是,我问这个以防我重新发明轮子,因为我对 React 很陌生。我的印象是,如果父组件通过 props 将其状态传递给子组件,而不是更新父组件的状态,则子组件将在需要时重新渲染。但情况似乎并非如此。我设置了这个例子,
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>
);
}
}
在这个例子中,除非我明确定义一个引用并使用它来调用孩子的更新函数(注释部分),否则每次更新父母的状态时都不会重新渲染孩子。是这样吗?您是想手动更新孩子的状态(呵呵),还是如果他们的父母的状态作为道具传递给他们,他们应该自动更新(并因此重新渲染)。
【问题讨论】:
-
所以基本上你是想在你的子组件中更新你父母的状态?
-
好吧,我不确定我是否会这样说。我将父变量的值传递给孩子。然后 child 呈现该值。假设将来父项中的变量更改了值,子项不应该根据父项的更改在屏幕上相应地更新自己。我正在尝试找出 props 是按值传递还是按引用传递,这是否有意义?
-
这是因为您的子组件也在使用自己的状态。你应该使用 props.number 来代替
-
是的,我需要使用孩子的道具而不是将它们存储到他们的状态中。我假设 props 仅用于传递数据,实际使用的所有内容都应存储在状态中。
标签: javascript reactjs react-props react-component react-state