3 回答

TA貢獻1803條經驗 獲得超3個贊
您的代碼中有一個小錯誤。當數組中沒有匹配的對象時,您應該在 map 函數之外而不是在它內部更新購物車。
import React, { createContext, useState, useEffect } from 'react';
import update from 'immutability-helper';
export const CartContext = createContext();
export function CartProvider(props) {
const [ cart, setCart ] = useState([]);
const addItem = (obj) => {
if (cart.length != 0) {
let dataExist = false;
cart.map((e, i) => {
if (e.productName === obj.productName) {
const object = e;
const cartCopy = cart;
const newObj = update(object, { quantity: { $set: object.quantity + 1 } });
const newState = update(cartCopy, { [i]: { $set: newObj } });
setCart(newState);
dataExist=true
}
});
if(dataExist) {
setCart([ ...cart, obj ]);
}
} else {
setCart([ ...cart, obj ]);
}
};
return <CartContext.Provider value={{ cart, addItem }}>{props.children} </CartContext.Provider>;
}
您的代碼所做的是這樣的,如果購物車數組中的當前 item(e) 與 obj 不匹配,則會將該 obj 添加到數組中。只有在您對數組進行迭代并確認數組中不存在與 obj 相同的數據后,才能執行此操作。
如果該更新不能解決您的問題,我可能需要您提供一些示例數據(即對象結構、示例輸出等)來正確測試。

TA貢獻1828條經驗 獲得超4個贊
請使用此更新您的代碼,如果您可以共享 obj 數據和購物車數據會更好:
const addItem = (obj) => {
if (cart.length !== 0) {
for (let i = 0; i <= cart.length; i += 1) {
if (undefined !== cart[i]) {
if (obj.productName === cart[i].productName) {
const tempArr = [...cart];
tempArr.quantity += 1;
setCart(tempArr);
} else {
setCart([...cart, obj]);
}
}
}
} else {
setCart([...cart, obj]);
}
};

TA貢獻1804條經驗 獲得超2個贊
我解決了!InsomniacSabbir 的想法是正確的。我只需要稍微修改代碼以獲得我想要的結果。
這是解決方案
import React, { createContext, useState, useEffect } from 'react';
import update from 'immutability-helper';
export const CartContext = createContext();
export function CartProvider(props) {
const [ cart, setCart ] = useState([]);
const addItem = (obj) => {
let dataCheck = true;
if (cart.length != 0) {
cart.map((e, i) => {
if (e.productName === obj.productName) {
const object = e;
const cartCopy = cart;
const newObj = update(object, { quantity: { $set: object.quantity + 1 } });
const newState = update(cartCopy, { [i]: { $set: newObj } });
setCart(newState);
dataCheck = false;
}
});
} else {
setCart([ ...cart, obj ]);
}
if (dataCheck === true) {
setCart([ ...cart, obj ]);
}
};
return <CartContext.Provider value={{ cart, addItem }}>{props.children}</CartContext.Provider>;
}
我在地圖中有一個 if/else 語句導致了問題。我從 map 中取出 else 語句,并將另一個 if 語句添加到檢查dataCheck是否為真/假的函數中。僅當 map 中的 if 語句被執行時,dataCheck才會被設置為 false。
添加回答
舉報