简体   繁体   中英

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

I set up a 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.

  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. 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. So keep your USD, GBP etc as mentioned in below code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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