简体   繁体   English

在React中如何在setState调用中使用字符串作为键

[英]How to use a string as the key in a setState call in React

I have a method in which I am attempting to call a state value for through a string. 我有一种尝试通过字符串调用状态值的方法。 Essentially, the string is "greeting" and the state value is greeting: "hello world". 本质上,字符串是“ greeting”,状态值是greeting:“ hello world”。

However, since the variable is a string "greeting", I am not able to call this.state.greeting with it and it gives me undefined. 但是,由于变量是一个字符串“ greeting”,因此我无法使用它来调用this.state.greeting,它使我不确定。 How can I convert a string to a variable so that it can be used to call this.state in React? 如何将字符串转换为变量,以便可以在React中调用this.state? I have experimented with the eval() method but it has not seemed to work. 我已经尝试过eval()方法,但是它似乎没有用。

this.state ['greeting']应该可以工作

您可以使用this.state [“ greeting”]

You can access it with javascript object bracket notation like so: 您可以使用javascript对象括号表示法来访问它,如下所示:

var myObj = {
  'greeting': 'hello world'
};

var myKey = 'greeting';

console.log(myObj[myKey]);        // 'hello world'

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

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