我看过this question,它帮助我理解了如何正确设置状态,但我很难找到基于变量的测试状态的正确格式。
例如,我有一个带有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}如何根据变量的值测试状态下的值?
发布于 2018-07-16 19:04:56
这就是你想要的:
var newItem = "tomato";
if(this.state.sandwichItems[newItem] === true { }https://stackoverflow.com/questions/51368532
复制相似问题