導覽列元件不會在狀態變更時重新渲染
P粉037880905
P粉037880905 2023-09-07 12:01:10
0
1
420

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

這是我創建上下文的地方

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>

狀態的值來自 useReducer,它正在更新一切正常

這就是我如何使用導覽列中的 useContext Hook 來取得購物車中的商品總數

const cartItems = useContext(CartContext);

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

但每當狀態改變時,導覽列都不會重新呈現更新後的購物車中的商品總數,請幫我。

這是我的 useReducer 函數及其更新的一切。我已經透過執行 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

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

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

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

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

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!