簡體   English   中英

用反應更新 state 中的對象數組

[英]updating array of objects in state with react

我正在嘗試使購物車做出反應,並希望能夠通過每次點擊來增加商品的數量。 我能找到的所有示例都只是將一個新項目推送到數組中,而不是增加現有項目的數量,結果如下:

[
{id: 1, item: pants, qty: 1},
{id: 1, item: pants, qty: 1},
{id: 2, item: shirt, qty: 1}
]

當我的目標是:

[
{id: 1, item: pants, qty: 2},
{id: 2, item: shirt, qty: 1}
]

我想出了下面的方法,但它非常難看。 我正在尋找更優雅的東西。

    function App() {

      const [items, setItems] = useState([]);

      const updateState = (item) => (e) => {
        let newArray = [...items];

        if (items.some((el) => el.id === item.id)) {
          const place = items.findIndex((obj) => obj.id === item.id);
          newArray[place] = {
            id: item.id,
            item: item.name,
            qty: items[place].qty + 1,
          };
        } else {
          newArray.push({ id: item.id, item: item.name, qty: 1 });
        }

        console.log(newArray);
        setItems(newArray);
     };

     return (
       <div>
         <button onClick={updateState({ id: 1, name: 'pants' })}></button>
         <button onClick={updateState({ id: 2, name: 'shirt' })}></button>
       </div>
     );
   }

這是一個工作的、丑陋的版本的代碼沙箱。 https://codesandbox.io/s/billowing-resonance-f1ip6?file=/src/App.js

你做得對。 最終會有一些庫可以幫助您使代碼更漂亮,例如DotProp ,但它只會處理您在幕后所做的事情。

最終,您可以通過直接獲取 indexOf 並檢查 if 語句中是否未定義來避免執行.some(...) ,但這並沒有太大變化。

你的實現很好,但為了保持干凈,我認為你應該創建一個新的 function ,它接受數組和項目,如果項目不存在則插入項目,如果項目存在於數組中,則更新項目的數量.

這是另一個實現。

 const arr = [ {id: 1, item: "pants", qty: 1}, {id: 2, item: "shirt", qty: 1} ] const addItem = (arr, item) => { const idx = arr.findIndex(el => el.id === item.id); if (idx === -1) { return [...arr, item] } arr[idx] = {...arr[idx], qty: arr[idx].qty + 1} return [...arr]; } let newArr = addItem(arr, {id: 1, item: "pants", qty: 1}) newArr = addItem(newArr, {id: 3, item: "jeans", qty: 1}) console.log(newArr)

我覺得這個不丑。 你能試試嗎?

import React from "react"
import "./styles.css"

export default function App() {
  const [items, setItems] = React.useState([
    {id: 1, name: 'pants'},
    {id: 2, name: 'shirt'}
  ])

  const handleClick = (i) => {
    setItems(items.map((item, curIndex) =>
           i === curIndex ? { ...item, qty: ++item.qty||1 } : item
    ))
  }

  return (
   <div>
     {items.map((item,index)=>(
       <button onClick={()=>handleClick(index)}>{item.qty || 0}</button>
     ))}
   </div>
 )
}

暫無
暫無

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

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