javascript - 我应该使用什么生命周期方法来监听状态变化并在反应类组件中相应地更新其他状态
问题描述
我正在开发一个应用程序,它有一个数据数组用户选择 timeSpan 等monthly
,weekly
根据该数组应该在屏幕上呈现。我试过这样做,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 });
}
解决方案
您不需要使用setState
从道具中选择特定的键。您应该使用setState
例如用户输入的数据。
const {timeSpan} = this.state;
let data;
if (timeSpan === "yearly" || timeSpan === "weekly") {
data = this.props.dispensingData.duration[timeSpan];
}
例如,您的渲染功能对于这个用例应该足够了。
推荐阅读
- python - 如果 cursor.executemany 在 Python 中失败会发生什么
- python - 跨多个列表的逻辑与运算
- wso2 - 错误:在 WSO2 身份服务器 5.10.0 中添加外部数据库作为主要用户存储时出现“用户管理员不存在”
- android - AsyncTask - 等待其他 Asynctask 的执行
- r - 使用 R 从给定的平均值、中值、SD、最大值和最小值生成数字
- xslt - 在字符串输入中提取分隔数据
- unit-testing - 尝试模拟 gremlin 查询时如何抛出异常?
- javascript - 求前 n num 的总和
- python - 使用 Django 将时间简单地保存为 UTC
- r - Looping through list of columns