导航栏组件不会在状态更改时重新渲染
P粉037880905
P粉037880905 2023-09-07 12:01:10
0
1
427

我正在尝试创建一个购物车。我创建了一个上下文,并在按购物车上的增量和减量按钮时将状态作为值传递,我的商品计数正在更改,但当我在导航栏组件中使用相同的上下文时,购物车中的商品总数不会更改。我附上下面的代码片段

这是我创建上下文的地方

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学习者快速成长!