亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

導(dǎo)覽列元件不會在狀態(tài)變更時重新渲染
P粉037880905
P粉037880905 2023-09-07 12:01:10
0
1
594

我正在嘗試創(chuàng)建一個購物車。我創(chuàng)建了一個上下文,並在按購物車上的增量和減量按鈕時將狀態(tài)作為值傳遞,我的商品計數(shù)正在更改,但當(dāng)我在導(dǎo)航欄組件中使用相同的上下文時,購物車中的商品總數(shù)不會更改。我附上下面的程式碼片段

這是我創(chuàng)建上下文的地方

const initialState:initialType = {
  cartItems:cartItems,
  totalItems:cartItems.reduce((accumulator, object) => {
    return accumulator + object.quantity
  }, 0),
  totalAmount:0
}

export const CartContext = createContext<initialType|null>(initialState);

下面是我的 useContext 提供者。

<CartContext.Provider value={{...state}}>
<ContextCart removeItems={removeItems} increment={increment} decrement={decrement}/> </CartContext.Provider>

狀態(tài)的值來自 useReducer,它正在更新一切正常

這就是我如何使用導(dǎo)覽列中的 useContext Hook 來取得購物車中的商品總數(shù)

const cartItems = useContext(CartContext);

return (
  <div>{cartItems.totalItems}</div>`
)

但每當(dāng)狀態(tài)改變時,導(dǎo)覽列都不會重新呈現(xiàn)更新後的購物車中的商品總數(shù),請幫我。

這是我的 useReducer 函數(shù)及其更新的一切。我已經(jīng)透過執(zhí)行 console.log() 檢查了它的功能。它返回的一切都很好,其中還包括 state.totalItems。

type actionType={
      type:string,
      payload:string
    }
    export const reducer = (state:initialType ,action:actionType) => {
      if(action.type === "Delete" ){
        return {
          ...state,
          cartItems:state.cartItems.filter((currentElement)=>{
            return currentElement.id != action.payload
          })
        }
      }
       if (action.type === 'increment'){
          state.cartItems.forEach((element)=>{
            if (element.id === action.payload){
              element.quantity++;
              state.totalItems++
            }
          })
         
          return {...state};
          
      }
      if (action.type === 'decrement'){
        state.cartItems.forEach((element)=>{
          if (element.id === action.payload){
            element.quantity--;
            state.totalItems--;
          }
        })
        console.log(state)
        return {...state};
      }
      return {...state};
    }```

P粉037880905
P粉037880905

全部回覆(1)
P粉348915572

當(dāng)您使用 useReducer 時,它會傳回目前狀態(tài),對吧?就你而言,該狀態(tài)是一個物件。因此,您可以直接從該狀態(tài)物件取得 totalItems 。例如:

const [state, dispatch] = useReducer(cartReducer, initialState);

// Here's where we get totalItems from the state
const { totalItems } = state;

因此,這樣,totalItems 就會從狀態(tài)物件直接拉出,您可以在任何需要的地方使用它。

最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板