我刚开始对简单的电子商务应用程序做出反应和工作。当添加多次时,我正在更改购物车中的数量,但它给出了错误的结果(正如我们在输出中看到的,我打印的"数量"和对象中的数量不同,例如之前:1之后:2,但在对象中是3(。我将感谢您的帮助。非常感谢。
这是我的reducer.js
export const initialState = {
basket : [],
}
const reducer = (state, action) => {
switch(action.type){
case "ADD_TO_BASKET":
const newIndex = state.basket.findIndex((basketItem)=> basketItem.id==action.item.id)
if(newIndex >= 0){
const newBasket = [...state.basket];
console.log(newBasket);
console.log("quantity "+newBasket[newIndex].quantity);
newBasket[newIndex].quantity+=action.item.quantity;
console.log(newBasket);
console.log("quantity "+newBasket[newIndex].quantity);
return{
...state,
basket: [...newBasket]
}
}
return{
...state,
basket: [...state.basket ,action.item]
}
.
.
.
export default reducer;
这是我的结账单.js:
import { useStateValue } from "./StateProvider"
function Checkout() {
const [{basket}, dispatch] = useStateValue();
return (
<div className='checkout'>
<div className="checkout__left">
<img src="https://images-na.ssl-images-amazon.com/images/G/02/UK_CCMP/TM/OCC_Amazon1._CB423492668_.jpg" alt="" className="checkout__ad" />
<div>
<h2 className='checkout__title'>
Your Shopping Basket
</h2>
{basket.map(item => (
// console.log("checkout product quantity: "+JSON.stringify(item.quantity)),
<CheckoutProduct
key={i++}
id = {item.id}
title = {item.title}
image = {item.image}
price = {item.price}
rating = {item.rating}
quantity = {item.quantity}
/>
))}
.
.
.
StateProvider.js:
import React, { createContext, useContext, useReducer } from 'react'
//prepares the data layer
export const StateContext = createContext();
//wrap our app and provide the data layer
export const StateProvider = ({ reducer, initialState, children }) => (
<StateContext.Provider value={useReducer(reducer, initialState)}>
{children}
</StateContext.Provider>
);
//pull infromation from the data layer
export const useStateValue = () => useContext(StateContext);
控制台输出:
-> [{…}]0: {---, quantity: 3}length: 1[[Prototype]]: Array(0)
-> quantity 1
->[{…}]0: {---, quantity: 3}---
-> quantity 2
请删除index.js文件中的React.StrictMode包装器。Strict模式是通过有意地双重调用某些函数来实现的。