假设在我的组件中我这样设置状态:
this.setState({
test: "value",
othertest: "value"
});
如果在我的代码的其他地方,我有一个包含这些值的键的数组,即 - keys = ["test", "othertest"]
我如何遍历这个数组来找到对应状态值的值?
最佳答案
State 是一个对象,因此您可以通过以下方式访问任何值:
this.state[key]
使用任何循环 map、forEach
等来迭代 array
并通过 this.state[key]
访问值,如下所示:
a.forEach(el => console.log(this.state[el]))
检查这个片段:
let state = {a: 1, b: 2};
let arr = ['a', 'b'];
let values = arr.map(el => state[el])
console.log(values);
关于javascript - 通过 react 中的动态键获取状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43985321/