首页 > 解决方案 > 将新对象推送到 React 中的对象嵌套数组

问题描述

我正在尝试将一个新对象添加到已调度的 Redux 初始状态中,但我似乎无法使其工作,因为它是新手。这是我的初始状态值

const initialState = {
  invoices: data,
  filterInvoice: data,
  toggleId: "",
  singleInvoice: [],
};

发票前面的数据是用于填充状态的本地 Json 数据。数据是一个对象数组。见下面的数据值

[
  {
    "id": "RT3080",
    "createdAt": "2021-08-18",
    "paymentDue": "2021-08-19",
    "description": "Re-branding",
    "paymentTerms": 1,
    "clientName": "Jensen Huang",
    "clientEmail": "jensenh@mail.com",
    "status": "paid",
    "senderAddress": {
      "street": "19 Union Terrace",
      "city": "London",
      "postCode": "E1 3EZ",
      "country": "United Kingdom"
    },
    "clientAddress": {
      "street": "106 Kendell Street",
      "city": "Sharrington",
      "postCode": "NR24 5WQ",
      "country": "United Kingdom"
    },
    "items": [
      {
        "name": "Brand Guidelines",
        "quantity": 1,
        "price": 1800.9,
        "total": 1800.9
      }
    ],
    "total": 1800.9
  },
  {
    "id": "XM9141",
    "createdAt": "2021-08-21",
    "paymentDue": "2021-09-20",
    "description": "Graphic Design",
    "paymentTerms": 30,
    "clientName": "Alex Grim",
    "clientEmail": "alexgrim@mail.com",
    "status": "pending",
    "senderAddress": {
      "street": "19 Union Terrace",
      "city": "London",
      "postCode": "E1 3EZ",
      "country": "United Kingdom"
    },
    "clientAddress": {
      "street": "84 Church Way",
      "city": "Bradford",
      "postCode": "BD1 9PB",
      "country": "United Kingdom"
    },
    "items": [
      {
        "name": "Banner Design",
        "quantity": 1,
        "price": 156.0,
        "total": 156.0
      },
      {
        "name": "Email Design",
        "quantity": 2,
        "price": 200.0,
        "total": 400.0
      }
    ],
    "total": 556.0
  },
]

继续,相同数据格式的对象将被分派到我的减速器中。所以我的问题是我不知道如何将对象添加到发票初始状态。我的减速机

if (action.type === ActionTypes.DynamicInput) {
    let tempInvoice;

    //calculate totalValues
    const totalAmount = action.payload.items.reduce((acc, curr) => {
      const { itemTotal } = curr;
      acc += parseFloat(itemTotal);
      return acc;
    }, 0);

    if (action.payload.createdAt) {
      const newDate = new Date(action.payload.createdAt).toLocaleDateString();
      const paymentDue = addDays(
        newDate,
        action.payload.paymentTerms
      ).toLocaleDateString();

      if (action.isDraft === true) {
        tempInvoice = {
          ...action.payload,
          createdAt: newDate,
          paymentDue: paymentDue,
          status: "draft",
          total: totalAmount,
        };
      } else {
        tempInvoice = {
          ...action.payload,
          createdAt: newDate,
          paymentDue: paymentDue,
          status: "pending",
          total: totalAmount,
        };
      }
    }

    // then initalizie the currentStates to add new action.payload objects coming from new invoice
    return {
      ...state,
      invoices: { ...state.invoices, tempInvoice },
    };
  }

我尝试使用扩展运算符来获取现有值并进行分配,但它可以正常工作

  return {
      ...state,
      invoices: [ ...state.invoices, tempInvoice ],
    };

标签: javascriptarraysreactjsjavascript-objects

解决方案


经过这么多调试以及发票数组为何发生变化后,我注意到 TempInvoice 返回空对象。即它没有被填充,它是空的。所以我重构了我的代码看起来像这样

if (action.payload.createdAt) {
      const newDate = new Date(action.payload.createdAt).toLocaleDateString();
      const paymentDue = addDays(
        newDate,
        action.payload.paymentTerms
      ).toLocaleDateString();

      if (action.isDraft === false) {
        tempInvoice = {
          ...action.payload,
          createdAt: newDate,
          paymentDue: paymentDue,
          id: getRandomAlphabet(),
          status: "draft",
          total: totalAmount,
        };
      } else {
        tempInvoice = {
          ...action.payload,
          createdAt: newDate,
          paymentDue: paymentDue,
          id: getRandomAlphabet(),
          status: "pending",
          total: totalAmount,
        };
      }
    } else {
      if (action.isDraft === false) {
        tempInvoice = {
          ...action.payload,
          status: "draft",
          id: getRandomAlphabet(),
          total: totalAmount,
        };
      } else {
        tempInvoice = {
          ...action.payload,
          status: "pending",
          id: getRandomAlphabet(),
          total: totalAmount,
        };
      }
    }
 return {
      ...state,
      invoices: [...state.invoices, tempInvoice],
     }
    };

推荐阅读