繁体   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