首页 > 解决方案 > 我应该使用什么生命周期方法来监听状态变化并在反应类组件中相应地更新其他状态

问题描述

我正在开发一个应用程序,它有一个数据数组用户选择 timeSpan 等monthlyweekly根据该数组应该在屏幕上呈现。我试过这样做,componentWillUpdate但我不确定。但这给了我错误。

用户可以从中选择timespan值的下拉菜单。我不知道我应该把它放在哪里,以便它监听timeSpan Any Help 中的变化会很棒

这是我的代码。

if (this.state.timeSpan === "yearly") {
      const yearlyData = this.props.dispensingData.duration["yearly"];
      this.setState({ spanData: yearlyData });
    } else if (this.state.timeSpan === "weekly") {
      const weeklyData = this.props.dispensingData.duration["weekly"];
      this.setState({ spanData: weeklyData });
    } 

标签: javascriptreactjs

解决方案


您不需要使用setState从道具中选择特定的键。您应该使用setState例如用户输入的数据。

const {timeSpan} = this.state;
let data;
if (timeSpan === "yearly" || timeSpan === "weekly") {
    data = this.props.dispensingData.duration[timeSpan];
}

例如,您的渲染功能对于这个用例应该足够了。


推荐阅读