useReducer:调度操作,在其他组件中显示状态,并在调度操作时更新状态



我有一个问题无法解决。我正在构建一个电子商务react应用程序,并使用useReduceruseContext进行状态管理。客户打开一个产品,选择一些项目,然后点击按钮";添加到购物车";其调度动作。这部分运行良好,问题开始了。我不知道如何在Navbar.js组件中显示和更新购物车中的产品总数。它在路线更改后显示,但我希望它在单击"添加到购物车"按钮时更新。我试过使用效果,但不起作用。

初始状态看起来像这个

const initialState = [
{
productName: '',
count: 0
}
]

AddToCart.js的效果很好

import React, { useState, useContext } from 'react'
import { ItemCounterContext } from '../../App'
function AddToCart({ product }) {
const itemCounter = useContext(ItemCounterContext)
const [countItem, setCountItem] = useState(0)
const changeCount = (e) => {
if (e === '+') { setCountItem(countItem + 1) }
if (e === '-' && countItem > 0) { setCountItem(countItem - 1) }
}
return (
<div className='add margin-top-small'>
<div
className='add-counter'
onClick={(e) => changeCount(e.target.innerText)}
role='button'
>
-
</div>
<div className='add-counter'>{countItem}</div>
<div
className='add-counter'
onClick={(e) => changeCount(e.target.innerText)}
role='button'
>
+
</div>
<button
className='add-btn btnOrange'
onClick={() => itemCounter.dispatch({ type: 'addToCart', productName: product.name, count: countItem })}
>
Add to Cart
</button>
</div>
)
}
export default AddToCart

Navbar.js是我遇到问题的地方

import React, { useContext } from 'react'
import { Link, useLocation } from 'react-router-dom'
import NavList from './NavList'
import { StoreContext, ItemCounterContext } from '../../App'
import Logo from '../Logo/Logo'
function Navbar() {
const store = useContext(StoreContext)
const itemCounter = useContext(ItemCounterContext)
const cartIcon = store[6].cart.desktop
const location = useLocation()
const path = location.pathname
const itemsSum = itemCounter.state
.map((item) => item.count)
.reduce((prev, curr) => prev + curr, 0)
const totalItemsInCart = (
<span className='navbar__elements-sum'>
{itemsSum}
</span>
)
return (
<div className={`navbar ${path === '/' ? 'navTransparent' : 'navBlack'}`}>
<nav className='navbar__elements'>
<Logo />
<NavList />
<Link className='link' to='/cart'>
<img className='navbar__elements-cart' src={cartIcon} alt='AUDIOPHILE CART ICON' />
{itemsSum > 0 ? totalItemsInCart : null}
</Link>
</nav>
</div>
)
}
export default Navbar

问题出在您的reducer中,特别是当您将以前的状态分配给newState以进行突变并返回更新的状态时。在JavaScript中,非基元是通过地址而不是值来引用的。由于作为数组的initialState恰好是非基元,因此当您将非基元分配给新变量时,该变量仅指向内存中的现有数组,而不会创建新副本。而且,只有当状态重建时(react就是这样理解有更新的(,而不是软突变时,才会触发/广播反应中的更新。当你突变并返回newState时,你基本上是在突变现有的state,而不是导致它重建。一个快速的解决方法是将state复制到newState中,而不仅仅是分配它。这可以使用排列运算符(...(来完成
在减速器功能中,更改:

const newState = state

const newState = [...state]

你的减速器功能应该是这样的:

export const reducer = (state, action) => {
// returns -1 if product doesn't exist
const indexOfProductInCart = state.findIndex((item) => item.productName === action.productName)
const newState = [...state] //Deep-copying the previous state
switch (action.type) {
case 'increment': {
if (indexOfProductInCart === -1) {
newState[state.length] = { productName: action.productName, count: state.count + 1 }
return newState
}
newState[indexOfProductInCart] = { productName: action.productName, count: state.count + 1 }
return newState
}
case 'decrement': {
if (indexOfProductInCart === -1) {
newState[state.length] = { productName: action.productName, count: state.count - 1 }
return newState
}
newState[indexOfProductInCart] = { productName: action.productName, count: state.count - 1 }
return newState
}
case 'addToCart': {
if (indexOfProductInCart === -1) {
newState[state.length] = { productName: action.productName, count: action.count }
return newState
}
newState[indexOfProductInCart] = { productName: action.productName, count: action.count }
return newState
}
case 'remove': return state.splice(indexOfProductInCart, 1)
default: return state
}
}

您似乎正在更改reducer函数中的state对象。首先用const newState = state保存对该状态的引用,然后用每个newState[state.length] = .....对该引用进行变异,然后用return newState为下一个状态返回相同的状态引用。下一个状态对象永远不是新的对象引用。

考虑以下使用各种数组方法在state数组上操作并返回数组引用的情况:

export const reducer = (state, action) => {
// returns -1 if product doesn't exist
const indexOfProductInCart = state.findIndex(
(item) => item.productName === action.productName
);
const newState = state.slice(); // <-- create new array reference
switch (action.type) {
case 'increment': {
if (indexOfProductInCart === -1) {
// Not in cart, append with initial count of 1
return newState.concat({
productName: action.productName,
count: 1,
});
}
// In cart, increment count by 1
newState[indexOfProductInCart] = {
...newState[indexOfProductInCart]
count: newState[indexOfProductInCart].count + 1,
}
return newState;
}
case 'decrement': {
if (indexOfProductInCart === -1) {
// Not in cart, append with initial count of 1
return newState.concat({
productName: action.productName,
count: 1,
});
}
// In cart, decrement count by 1, to minimum of 1, then remove
if (newState[indexOfProductInCart].count === 1) {
return state.filter((item, index) => index !== indexOfProductInCart);
}
newState[indexOfProductInCart] = {
...newState[indexOfProductInCart]
count: Math.max(0, newState[indexOfProductInCart].count - 1),
}
return newState;
}
case 'addToCart': {
if (indexOfProductInCart === -1) {
// Not in cart, append with initial action count
return newState.concat({
productName: action.productName,
count: action.count,
});
}
// Already in cart, increment count by 1
newState[indexOfProductInCart] = {
...newState[indexOfProductInCart]
count: newState[indexOfProductInCart].count + 1,
}
return newState;
}
case 'remove':
return state.filter((item, index) => index !== indexOfProductInCart);
default: return state
}
}

Navbar中的itemsSum现在应该可以从上下文中看到状态更新。

const itemsSum = itemCounter.state
.map((item) => item.count)
.reduce((prev, curr) => prev + curr, 0);

它还显示您已经在具有空依赖数组的useMemo挂钩中存储了state值。这意味着传递给StoreContext.Providercounter值永远不会更新。

function App() {
const initialState = [{ productName: '', count: 0 }];
const [state, dispatch] = useReducer(reducer, initialState);
const counter = useMemo(() => ({ state, dispatch }), []); // <-- memoized the initial state value!!!
return (
<div className='app'>
<StoreContext.Provider value={store}> // <-- passing memoized state
...
</StoreContext.Provider>
</div>
)
}

state添加到依赖数组

const counter = useMemo(() => ({ state, dispatch }), [state]);

或者根本不记忆它,并将statedispatch传递到上下文value

<StoreContext.Provider value={{ state, dispatch }}>
...
</StoreContext.Provider>

好吧,ItemCounterContext对这个问题很重要,只需忽略StoreContext,它适用于图像。。。这是一个减速器函数。

export const reducer = (state, action) => {
// returns -1 if product doesn't exist
const indexOfProductInCart = state.findIndex((item) => item.productName === action.productName)
const newState = state
switch (action.type) {
case 'increment': {
if (indexOfProductInCart === -1) {
newState[state.length] = { productName: action.productName, count: state.count + 1 }
return newState
}
newState[indexOfProductInCart] = { productName: action.productName, count: state.count + 1 }
return newState
}
case 'decrement': {
if (indexOfProductInCart === -1) {
newState[state.length] = { productName: action.productName, count: state.count - 1 }
return newState
}
newState[indexOfProductInCart] = { productName: action.productName, count: state.count - 1 }
return newState
}
case 'addToCart': {
if (indexOfProductInCart === -1) {
newState[state.length] = { productName: action.productName, count: action.count }
return newState
}
newState[indexOfProductInCart] = { productName: action.productName, count: action.count }
return newState
}
case 'remove': return state.splice(indexOfProductInCart, 1)
default: return state
}
}

这里是App.js,我在这里与其他组件共享状态

import React, { createContext, useMemo, useReducer } from 'react'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import Navbar from './components/Navbar/Navbar'
import Homepage from './pages/Homepage/Homepage'
import Footer from './components/Footer/Footer'
import ErrorPage from './pages/ErrorPage/ErrorPage'
import SelectedCategory from './pages/SelectedCategory/SelectedCategory'
import SingleProduct from './pages/SingleProduct/SingleProduct'
import ScrollToTop from './services/ScrollToTop'
import store from './services/data.json'
import { reducer } from './services/ItemCounter'
import './scss/main.scss'
export const StoreContext = createContext(store)
export const ItemCounterContext = createContext()
function App() {
const initialState = [{ productName: '', count: 0 }]
const [state, dispatch] = useReducer(reducer, initialState)
const counter = useMemo(() => ({ state, dispatch }), [])
return (
<div className='app'>
<StoreContext.Provider value={store}>
<ItemCounterContext.Provider value={counter}>
<Router>
<ScrollToTop />
<Navbar />
<Routes>
<Route path='/' element={<Homepage />} />
<Route path='/:selectedCategory' element={<SelectedCategory />} />
<Route path='/:selectedCategory/:singleProduct' element={<SingleProduct />} />
<Route path='*' element={<ErrorPage />} />
</Routes>
<Footer />
</Router>
</ItemCounterContext.Provider>
</StoreContext.Provider>
</div>
)
}
export default App

我很清楚你在说什么,但reducer的问题是只有可变方法才能处理状态。像.slice((、.contat((甚至spread运算符[…state]这样的不可变方法都不起作用,我不知道为什么:(我尝试了这两个答案,但调度(操作(并不能改变状态。也许初始状态是问题所在,我会试着把它像一样

initialState={购物车:[productName:",计数:0]}

最新更新