【问题标题】:REACT how to store an Object instead of an Array of Objects in setState?REACT 如何在 setState 中存储对象而不是对象数组?
【发布时间】:2019-02-16 15:45:53
【问题描述】:
  1. 我正在尝试将数据存储为一个对象并且我得到一个对象数组,我试图在不改变作为实际对象数组的原始状态对象的情况下执行此操作,这是为了我的前端逻辑,它使如果我有一个简单的 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}

【问题讨论】:

  • 您的问题不够清楚,无法提供答案。
  • 感谢您花时间阅读本文,基本上,当我 setState 时,它​​会在 this.state.currencies 中创建一个对象数组,并且我试图仅获取示例状态的对象。跨度>
  • 一个对象如何包含相同的键?你在一个对象中有相同的键做什么?这没有意义
  • @Think-Twice 我这样做是为了更快地键入它,但我不想拥有相同的键,只是为了从数组中删除它们并创建一个简单的对象。

标签: arrays reactjs object properties setstate


【解决方案1】:

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

执行以下操作

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-03
    • 2020-10-22
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多