javascript - 在 React 中测试状态对象
问题描述
我已经看到了这个问题,它有助于我理解如何正确设置状态,但我正在努力解决基于变量的测试状态的正确格式。
例如,我有setState
一个带有newItem
变量的函数调用:
addToSandwich(newItem){
setState(prevState => {
return { sandwichItems: {...prevState.sandwichItems, [newItem]: true} };
});
}
并假设当前状态如下所示:
sandwichItems: {
meat: true,
cheese: true,
tomato: false
}
和var newItem = "tomato";
这将导致:
sandwichItems: {
meat: true,
cheese: true,
tomato: true
}
但我无法通过以下方式测试 newItem:
var newItem = "tomato";
if (this.state.sandwichItems.newItem === true) {//whatever}
我必须这样做:
if (this.state.sandwichItems.tomato === true) {//whatever}
如何根据变量的值测试状态值?
解决方案
这就是你想要的:
var newItem = "tomato";
if(this.state.sandwichItems[newItem] === true { }
推荐阅读
- javascript - 使用不同的企业 ID 时,信任试点轮播不起作用
- php - redis大通道数性能
- php - 使用 PHP 将 JSON 中的“false”值转换为空字符串
- php - Joomla 插件将 Javascript 片段注入所有页面
- android - 在 Outterclass 中应用更改的 Runnable 匿名类模拟示例?
- ios - 无法在桥文件中导入“fscalendar.h”
- html - 如何使手风琴面板可点击,而不仅仅是文本
- objective-c - 读取对象上未找到的字典元素的预期方法
- r - 用相同位数的随机数替换数字
- hive - Hive 表是 MANAGED 或 EXTERNAL - 发布表类型转换