简体   繁体   English

在React中测试状态对象

[英]Testing State Objects in React

I've seen this question and it's helped with my understanding of how to set state correctly, but I'm struggling with the correct format of testing state based on a variable. 我已经看到了这个问题 ,这有助于我理解如何正确设置状态,但是我正在努力尝试基于变量测试状态的正确格式。

For example, I have this setState function call with a newItem variable: 例如,我有setState带有newItem变量的setState函数调用:

addToSandwich(newItem){

    setState(prevState => {
        return { sandwichItems: {...prevState.sandwichItems, [newItem]: true} };
    });

}

And assuming the current state looks like this: 并假设当前状态如下所示:

sandwichItems: {
    meat: true,
    cheese: true,
    tomato: false
}

With var newItem = "tomato"; var newItem = "tomato";

It would result in this: 这将导致以下结果:

sandwichItems: {
    meat: true,
    cheese: true,
    tomato: true
}

But I am unable to test for newItem with: 但是我无法使用以下方法测试newItem:

var newItem = "tomato";

if (this.state.sandwichItems.newItem === true) {//whatever}

I would have to do: 我将要做:

if (this.state.sandwichItems.tomato === true) {//whatever}

How do I test for a value in state based on a variable's value? 如何根据变量的值测试状态值?

This is what you want: 这就是你想要的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM