简体   繁体   English

REACT如何在setState中存储对象而不是对象数组?

[英]REACT how to store an Object instead of an Array of Objects in setState?

  1. I'm trying to store data as an Object and I get an Array of Objects, I'm trying to do this without mutating the original state Object which is an actual array of Objects, this is for my frontend logic which makes it straightforward if I have a simple Object(dict). 我正在尝试将数据存储为一个对象,并且得到一个对象数组,我试图在不改变原始状态Object的情况下做到这一点,Object是一个实际的Objects数组,这是出于我的前端逻辑,如果我有一个简单的Object(dict)。

I set up a CodeSandbox 我设置了一个CodeSandbox

basically, im getting this: 基本上,我得到这个:

currencies: [{MXN: "10"},{USD: "10"},{GBP: "10"}]

and im looking for this: 我正在寻找这个:

currencies: {MXN: "10", USD: "10", GBP: "10"}

shortened for easy reading, you can try it out in the CodeSandbox , just check the console it's ready. 为方便阅读而缩短了时间,您可以在CodeSandbox中尝试一下,只需检查控制台是否已准备就绪。

  1. If there is a known way to avoid creating the new state and just using the first one please let me know how to or where can I read about it, I'm still learning React. 如果有避免创建新状态的已知方法,而仅使用第一个状态,请告诉我如何或在何处可以了解到它,我仍在学习React。 I was trying to create a property inside the class to store the values there but I think I'm not understanding how it works. 我试图在类中创建一个属性以在其中存储值,但我认为我不了解它的工作原理。

Something kind of like this: 像这样的东西:

currencies = {MXN: this.state.axiosCurrencies[0].value, 
              USD: this.state.axiosCurrencies[1].value, 
              GBP: this.state.axiosCurrencies[2].value}

The axiosCurrencies state should contain a key name and as well as value to generate an object as you need. axiosCurrencies状态应包含键名和值,以根据需要生成对象。 So keep your USD, GBP etc as mentioned in below code. 因此,请按照以下代码中的说明保留您的USD,GBP等。

Do something like below 做下面的事情

    //keep your currencies as an object in state
    constructor(props){
          this.state = {
             currencies: {},
               // you need to construct your data axiosCurrencies like below
            axiosCurrencies: [{“id”: “01”, “name”: “MXN”, “value”: “abc”}, {“id”: “02”, “name”: “USD”, “value”: “xyz”}, {“id”: “03”, “name”: “GBP”, “value”: “def”}]
         }
    }

     //you can do below iteration in either componentDidMount or componentWillReceiveProps. Use componentWillReceiveProps if you are not using react v16.3 or greater version because this method is deprecated in latest versions.

    //do something like below to construct an object as you need.
    const obj = {};
    const { axiosCurrencies } = this.state;
     axiosCurrencies.forEach((item, index) => {
           obj[item.name] = item.value;
     });
     this.setState({
         currencies: obj
     });

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

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