簡體   English   中英

這個redux動作和減速器有什么問題?

[英]What is the problem in this redux action and reducer?

我知道,一旦該組件的狀態發生更改,redux觸發器將對組件進行重新渲染,但這在我的情況下不會發生。

行動

const addToCart = (product, cartProducts) => {
   let newCartProducts = [...cartProducts, product];

   newCartProducts = newCartProducts.reduce((acc, cur) => {
      let repeated = acc.find(p => p.id === cur.id);
      if(repeated)  repeated.quantity++;   
      else acc.push(cur);
      return acc;
    }, []);

    return {
      type: ADD_TO_CART,
      payload: newCartProducts
    }
}

減速器

export default (state = [], action) => {
    switch (action.type) {
        case ADD_TO_CART:
            return action.payload;
        default:
            return state;
    }

}

每次從組件分派動作時,reducer都會返回一個新狀態,但是我需要關閉購物車並再次打開才能獲得效果,redux不會同時更新產品數量?

您正在修改狀態中的現有元素。

采用

newCartProducts = newCartProducts.reduce((acc, cur) => {
  let repeatedIndex = acc.findIndex(p => p.id === cur.id);
  const repeated = acc[repeatedIndex];
  if (repeated) {
    acc[repeatedIndex] = { 
      ...repeated,
      quantity: repeated.quantity + 1
    };
  } else acc.push(cur);
  return acc;
}, []);

每次都會重新創建數組,但數組中的對象不會被重新創建。 因此,當您修改其內部時,您需要通知特定對象已更改。

重構邏輯到減速器並在此處設置數量:

const addToCart = product => {
  return {
    type: ADD_TO_CART,
    payload: product,
  };
};
//I assume state is an array of products on your cart
export default (state = [], action) => {
  switch (action.type) {
    case ADD_TO_CART:
      const { id } = action.payload;
      return state.map(p => p.id).includes(id)
        ? //product is already on card add quanity
          state.map(p =>
            p.id === id
              ? { ...p, quantity: p.quantity + 1 }
              : p
          )
        : state.concat({ ...action.payload, quantity: 1 }); // add product
    default:
      return state;
  }
};

暫無
暫無

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

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