【问题标题】:update state in useReducer()在 useReducer() 中更新状态
【发布时间】:2022-01-05 02:37:10
【问题描述】:

首先我不得不提一下,我对反应有点陌生,但我花了几个小时来解决useReducer 的问题,但我无法理解。这是我的代码:

const defaultCartState = {
items: [],
totalAmount: 0,
};
//action = {type:"ADD" , item:item}
const cartReducer = (state, action) => {
if (action.type === "ADD") {
    const updatedTotalAmount = parseFloat(
    state.totalAmount + action.item.price * action.item.amount
    ).toFixed(2);

    const existingCartItemIndex = state.items.findIndex(
    (item) => item.id === action.item.id
    );
    const existingCartItem = state.items[existingCartItemIndex];

    let updatedItems;
    if (existingCartItem) {
        const updatedItem = state.items[existingCartItemIndex];
        updatedItem.amount =
        state.items[existingCartItemIndex].amount + action.item.amount;
        const updatedItems = [...state.items];
        updatedItems[existingCartItemIndex] = updatedItem;
        return {
          items: updatedItems,
          totalAmount: updatedTotalAmount,
        };
        } else {
             const updatedItems = state.items.concat(action.item);
        return {
             items: updatedItems,
             totalAmount: updatedTotalAmount,
        };
     }
}
return defaultCartState;
};

它只是我的减速器函数state 包含一个名为items 的数组,该数组的每个元素都是一个具有amount 值的对象。这是我的useReducer 初始化:

 const [cartState, dispatchCartAction] = useReducer(cartReducer,defaultCartState);

我的问题在于这两行代码:

if (existingCartItem) {
   const updatedItem = state.items[existingCartItemIndex];
   updatedItem.amount =
   state.items[existingCartItemIndex].amount + action.item.amount;

如果我将这两行代码换成这些,一切正常。

if (existingCartItem) {
  const updatedItem = {
    ...existingCartItem,
    amount: existingCartItem.amount + action.item.amount,
  };

我想知道是什么问题?为什么我的方法不起作用?定义像我的解决方案这样的项目和真正的解决方案有什么区别? 提前谢谢你

【问题讨论】:

    标签: reactjs react-hooks use-reducer


    【解决方案1】:

    由于 reducer 是纯函数,你不能直接改变状态。这就是为什么第二种方法有效的原因。您需要复制以前的状态,然后每次都创建一个新对象。

    我认为this 可能会有所帮助(如果我理解正确的话);

    【讨论】:

    • 但我的问题是,在第一种方法中,我也没有改变实际状态。我刚刚定义了一个新的 const updatedItem 但根本没有改变我的状态。我错了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 2020-06-07
    • 2022-01-10
    • 1970-01-01
    • 2021-03-02
    • 2023-04-11
    • 2019-08-13
    相关资源
    最近更新 更多