簡體   English   中英

在 useState React 中更新數組內的對象

[英]Update object inside an array in useState React

我在 useState 中有一個對象,其中有一個名為 detail 的數組。 該數組包含我需要更新的對象,例如更改數量或購買價格。

createdAt: "2022/07/15"
detail: Array(2)
0:
name: "LINK AZUL"
provider: {uid: '6271a32082193f4b88e292f0', name: 'Genérico'}
purchasePrice: 195
quantity: 3
subtotal: 585
total: 0
_id: "62ab8f3cd0519268de938c8f"
[[Prototype]]: Object
1: {provider: {…}, _id: '62ab8ed6d0519268de938bc9', name: 'LINK ROJO', quantity: 3, purchasePrice: 186, …}
length: 2
[[Prototype]]: Array(0)
disabledBy: []
discount: 10
idProvider: {_id: '6271a32082193f4b88e292f0', name: 'Genérico'}

如何訪問詳細數組中對象的 _id 以便能夠對其進行修改並將其設置為 useState?

我已經嘗試使用此代碼搜索 _id 但后來我不知道如何在名為 detail 的對象數組中設置它,以便只修改該對象而不更改其余對象除此之外,我認為它不會正常工作。

const onChangePriceHandler = (id, e) => {
        let newPrice = Number(e.target.value)
       
        const updatePrice = products.detail?.map(data => {
          if (data.id === id) {
            return {
              ...data, purchasePrice: newPrice, subtotal: newPrice * data.quantity
            }
        } 
            return data
        })
        setProducts( /* ?? */)
      }

您可以通過這樣做來更新狀態

const onChangePriceHandler = (id, e) => {
        let newPrice = Number(e.target.value)
       
        const newProducts= products?.map(product=> {
            const dataIndex = (product.detail || []).findIndex((_data) => _data._id === id);
            const detail =
              dataIndex > 0
                ? [...product.detail].splice(dataIndex, 1, {
                    ...product.detail[dataIndex],
                    purchasePrice: newPrice,
                    subtotal: newPrice * product.detail[dataIndex].quantity,
                  })
                : product.detail;
          return dataIndex > 0
            ? {
                ...product,
                detail,
              }
            : product;
        })
        setProducts( [...newProducts]) //<---
      }

您可以做的是將狀態保存到一個變量中,然后將該變量的 id 更新為您想要的,然后將狀態設置為該更新后的變量

  const functionThatUpdatesTheState = ()=> {
    let variable = stateValueWeHaveNow;
    variable......id = theUpdatedId; 
    setState(variable)
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM