简体   繁体   English

如何在 ReactJS 中更新对象的 setstate

[英]How can I updating setstate for object in ReactJS

I have two objects: first state我有两个对象:第一个状态

[{ "orders": [{ "id": "1587881", "uid": "237603" }, { "id": "1587880", "uid": "237603" }] }]

and add new data并添加新数据

[{ "orders": [{ "id": "1587879", "uid": "237603" }, { "id": "1587878", "uid": "237603" }] }]

i need get new state我需要获得新的状态

[{ "orders": [{ "id": "1587881", "uid": "237603" }, { "id": "1587880", "uid": "237603" }, { "id": "1587879", "uid": "237603" }, { "id": "1587878", "uid": "237603" }] }]

Pleas help me!请帮助我!

I try it我试试

import React, { Component } from 'react';

class Orders extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [{ "orders": [{ "id": "1587881", "uid": "237603" }, { "id": "1587880", "uid": "237603" }] }]
    };
  }

  loadingData = () => {
    const add = [{ "orders": [{ "id": "1587879", "uid": "237603" }, { "id": "1587878", "uid": "237603" }] }];
    this.setState({ data: [...this.state.data, ...add] });
  }

  componentDidMount() {
    this.loadingData();
  }

  render() {

    console.log(this.state.data);


    return (
      <div className="page" >
      </div>
    );
  }
}

export default Orders;

But I am not getting a single array of data ... two separate arrays are created.但是我没有得到单个数据数组……创建了两个单独的数组。 How can I fix this?我怎样才能解决这个问题?

PS I am receiving data in this format and I cannot fix the format of the object. PS 我正在接收这种格式的数据,但我无法修复对象的格式。

You are saying that the state data is an array of objects, this response is assuming that you will add orders to the same first index on that array.您是说状态data是一个对象数组,此响应假设您将向该数组的相同第一个索引添加订单。

loadingData = () => {
    const add = [{ "orders": [{ "id": "1587879", "uid": "237603" }, { "id": "1587878", "uid": "237603" }] }];
    this.setState(oldState => {
      const newData = { ...oldState.data };
      add[0].orders.forEach(x => newData[0].orders.push(x));
      return { data: newData };
    });
  }

Here a working example: https://codesandbox.io/s/elated-lederberg-i3rtb?file=/src/App.js这是一个工作示例: https : //codesandbox.io/s/elated-lederberg-i3rtb?file=/src/App.js

You can do destructering on the first element of the array and then rebuild the way you want.您可以对数组的第一个元素进行解构,然后按照您想要的方式重建。

  const array1 = [
{
  orders: [
    { id: "1587881", uid: "237603" },
    { id: "1587880", uid: "237603" }
  ]
}
];
const array2 = [
{
  orders: [
    { id: "1587879", uid: "237603" },
    { id: "1587878", uid: "237603" }
  ]
}
];

const [firstEl] = array1;
const [secondEl] = array2;
console.log([{ orders: { ...firstEl.orders, ...secondEl.orders } 
}]);

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

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