【发布时间】:2019-05-16 16:31:50
【问题描述】:
场景是,在安装组件后,在事件监听器中,我正在设置一个状态变量,而其他状态变量正在通过从后端进行休息调用来设置。
到目前为止,我正在使用 componentWillUpdate 并进行休息调用并设置所有必需的状态。
我尝试使用 componentWillUpdate 方法来计算和设置其他状态变量。但是它多次重新渲染。我想我肯定在这里做错了。
export default class Person extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
name: this.props.name,
age: "",
country: ""
};
}
componentDidMount() {
this.setDerivedStates();
}
componentWillUpdate() {
this.setDerivedStates();
}
attachListner() {
document.addEventListner("customEvent", () => {
this.setState({ name: something });
});
}
setDerivedStates() {
FetchService.get("url1" + this.state.name).then(response =>
this.setState({ age: response.age})
);
FetchService.get("url2" + this.state.name).then(response =>
this.setState({ country: response.country })
);
}
render() {
return (
<div>
<p>{this.state.name}</p>
<p>{this.state.age}</p>
<p>{this.state.country}</p>
</div>
);
}
}
我想用所有新的状态变量重新渲染组件一次。 请建议我该怎么做。我应该使用哪种生命周期方法以及如何设置所有这些状态?
【问题讨论】:
-
它应该在每次状态更新时重新渲染。为什么这是个问题?如果你想减少
setStates的数量,你可以在setDerivedStates()中使用Promise.all,这会简化一点,但总的来说,这应该不是问题,因为 React 正在按预期工作。 -
你忘记了
setDerivedStates();中的this. -
@larz 它再次重新渲染,我想减少它。在我读到的某个地方,我们不应该在 componentWillUpdate 方法中执行 setState。所以我有点怀疑我使用了错误的生命周期方法。但不确定我还应该使用什么。
-
@Vencovsky 感谢伙伴更新了它。