首页 > 解决方案 > 在 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}

如何根据变量的值测试状态值?

标签: javascriptreactjsstate

解决方案


这就是你想要的:

var newItem = "tomato";
if(this.state.sandwichItems[newItem] === true { }

推荐阅读