- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我遇到了一个我无法解决的问题。我正在构建一个电子商务 react 应用程序并使用 useReducer
和 useContext
进行状态管理。客户打开产品,挑选商品数量,然后单击“添加到购物车”按钮以发送操作。这部分工作正常,问题开始了。我不知道如何在 Navbar.js
组件中显示和更新购物车中的产品总数。它在路线更改后显示,但我希望在单击“添加到购物车”按钮时更新它。我试过 useEffect 但它不起作用。
初始状态是这样的
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 中,仅当状态被重建时(这就是 React 理解存在更新的方式)而不是软变异时才会触发/广播更新。当您改变并返回 newState
时,您基本上改变了现有的 state
而不是导致它重建。一个快速的解决方法是将您的 state
复制到 newState
而不仅仅是分配它。这可以使用扩展运算符 (...
) 来完成。
在你的 reducer 函数中,更改:
const newState = state
到
const newState = [...state]
你的 reducer 函数应该看起来像这样:
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
}
}
关于javascript - useReducer : dispatch action, 在其他组件中显示状态并在分派(dispatch)操作时更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70713866/
我的密码 https://gist.github.com/ButuzGOL/707d1605f63eef55e4af 因此,当我收到登录成功回调时,我想进行重定向, 重定向也可以通过调度程序进行。 我
我已经写了访问者模式如下,但我不明白什么是单次和双次分派(dispatch)。AFAIK,单分派(dispatch)是根据调用者类型调用方法,而双分派(dispatch)是根据调用者类型和参数类型调用
我有一个非 ui 线程,我需要在该线程上发送消息。 执行此操作的正常方法是在我的线程的线程过程中调用 Dispatcher.Run()。 我想修改它以使其在处理未处理的异常方面更加健壮。 我的第一个剪
我有一个具有这样功能的代码 const mapDispatchToProps = (dispatch: Dispatch) => ({ onAddProduct: ( key: str
我在使用 Window.Show 显示 WPF 窗口时遇到问题: System.InvalidOperationException was unhandled Message: An unhandle
我对何时使用 Dispatcher.Invoke 从不同线程更新 UI 上的某些内容存有疑问。 这是我的代码... public Window4() { InitializeC
我遇到了一个我无法解决的问题。我正在构建一个电子商务 react 应用程序并使用 useReducer 和 useContext 进行状态管理。客户打开产品,挑选商品数量,然后单击“添加到购物车”按钮
尽管我已经深入了解了 NEventStore 上的事务完整性,但我无法理解在连接了许多 NEventStore 实例时 NEventStore 将如何真正扩展。 总结一下我的理解,一个事件被添加到提交
我学习了 React Javascript 和 Redux,现在我遇到了这个问题。 这是一个 codesandbox 像这样尝试: 搜索书名“dep” 观察日志显示“Search url is:”,当
Dispatcher.CurrentDispatcher(在System.Windows.Threading中)和Application.Current.Dispatcher(在 >系统.Window
我得到了一些代码来处理调度程序在其构造函数中传递给 View 模型的位置。我现在想知道当我想要在 UI 线程上执行某些操作时,我是否应该使用 ObserveOn(dispatcher) 或 dispa
当我们的一个应用程序服务器内存不足时,我正在分析 Java 堆转储。我正在使用 Eclipse 内存分析器。它报告了以下内容。 One instance of "akka.dispatch.Dispa
哪一个: public static let barrier: DispatchWorkItemFlags public static let detached: DispatchWorkItem
我想使用不同于调度类型的类型提示 Action 创建者。 我已经尝试使用这两种类型对 ThunkResult 进行类型提示,但这并不理想。 // types.ts interface AppListA
我正在尝试准确地理解什么是单次分派(dispatch)和多次分派(dispatch)。 我刚刚读到这个: http://en.wikipedia.org/wiki/Multiple_dispatch
I have following api returning Flux of String我有以下返回字符串通量的接口 @GetMapping(value = "/api/getS
这是我自学前端开发一年后在Stackoverflow上的第一个问题。我已经找到了我的疑惑的答案,但由于这些问题是第三次返回,我认为是时候向 Web 提问了。 我正在尝试构建什么 我正在尝试构建一个图书
我正在使用 Kotlin 学习 Android,并且我了解到在不阻塞主线程的情况下启动协程的推荐方法是执行以下操作 MainScope().launch { withContext(Dispatc
错误本身: (alias) deleteCategory(id: number): (dispatch: Dispatch) => void import deleteCategory Argumen
我必须对抽屉进行裁剪,然后创建一个包含所有需要项的DrawerComponent,并创建一个带有NavigationActions的函数来调度我的路线,但是它不起作用。当我单击任何项目时,我都会遇
我是一名优秀的程序员,十分优秀!