如何在反应本机中设置数组并从键中获取值 [英] How to set an array and get values from key in react native

查看:55
本文介绍了如何在反应本机中设置数组并从键中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是将数组设置为状态,例如:

What I would like to do is to set an array as a state for example :

state={
array : ['key1': 'value1', 'key2': 'value2', 'key3': 'value3']
};

我还想通过一种方法访问其中一个值的键,例如 getValue(key1)

I also would like to access with a method one of the values by its key for example getValue(key1)

推荐答案

如果您使用的是类组件

class YourClassComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      array: ['key1': 'value1', 'key2': 'value2', 'key3': 'value3']
    };
  }

  getValue = (key) => {
    return this.state.array[key];
  }
}

Else 在带有 React Hooks


import {useState} from 'react'; // <------- Import useState

const YourFunctionComponent = () => {

  const [array, setArray] = useState(['key1': 'value1', 'key2': 'value2', 'key3': 'value3']); //  <------- By default create with these values

  const getValue = (key) => {
   return array[key];
  }

}

这篇关于如何在反应本机中设置数组并从键中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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