繁体   English   中英

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

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

  1. 我正在尝试将数据存储为一个对象,并且得到一个对象数组,我试图在不改变原始状态Object的情况下做到这一点,Object是一个实际的Objects数组,这是出于我的前端逻辑,如果我有一个简单的Object(dict)。

我设置了一个CodeSandbox

基本上,我得到这个:

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

我正在寻找这个:

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

为方便阅读而缩短了时间,您可以在CodeSandbox中尝试一下,只需检查控制台是否已准备就绪。

  1. 如果有避免创建新状态的已知方法,而仅使用第一个状态,请告诉我如何或在何处可以了解到它,我仍在学习React。 我试图在类中创建一个属性以在其中存储值,但我认为我不了解它的工作原理。

像这样的东西:

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

axiosCurrencies状态应包含键名和值,以根据需要生成对象。 因此,请按照以下代码中的说明保留您的USD,GBP等。

做下面的事情

    //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