通过动态密钥获取状态值 [英] Get state value by a dynamic key in react

查看:109
本文介绍了通过动态密钥获取状态值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说在我的组件中我设置状态如下:

Let's say in my component I set the state like so:

this.setState({
      test: "value",
      othertest: "value"        
});

如果在我的代码的其他地方,我有一个包含这些值的键的数组,即 - keys = [test,othertest] 如何循环遍历此数组以查找相应状态值的值?

If, elsewhere in my code, I have an array containing the keys for these values, ie- keys = ["test", "othertest"] how can I loop through this array to find the value of the corresponding state value?

推荐答案

状态是一个对象,因此您可以通过以下方式访问任何值:

State is an object, so you can access any value by:

this.state[key]

使用任何循环 map,forEach 等迭代数组并通过 this.state [key] 访问该值code>,像这样:

Use any loop map, forEach etc to iterate the array and access the value by this.state[key], like this:

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);

这篇关于通过动态密钥获取状态值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆