当我向购物车中添加东西时出现此错误。我已经检查了代码很多次,但我仍然找不到解决方案,我不知道如何使它工作。
cartActions.js中的代码
import axios from 'axios'
import { CART_ADD_ITEM } from '../constants/cartConstants';
export const addToCart = (id, qty) => async (dispatch, getState) => {
const { data } = await axios.get(`/api/products/${id}`)
dispatch({
type: CART_ADD_ITEM,
payload: {
product: data._id,
name: data.name,
image: data.image,
price: data.price,
countInStock: data.countInStock,
qty
}
})
localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems))
}
cardReducers.js中的代码我想问题出在这里,但我不知道该从哪里改
import { CART_ADD_ITEM } from "../constants/cartConstants"
export const cartReducer = (state = { cartItems: [] }, action) => {
switch (action.type) {
case CART_ADD_ITEM:
const item = action.payload
const existItem = state.cartItems.find(x => x.product === item.product)
if(existItem){
return{
...state,
cartItems: state.cartItems.map(x =>
x.product === existItem.product ? item:x)
}
}else{
return{
...state,
cartItems:[...state.cartItems, item]
}
}
default:
return state;
}
}
CartScreen.js中的代码
import React, {useEffect} from 'react'
import { useParams, useLocation } from 'react-router-dom';
import { useDispatch, useSelector} from 'react-redux';
import { Row, Col, ListGroup, Image, Form, Button, Card } from 'react-bootstrap';
import { Message } from '../components/Message';
import { addToCart } from '../actions/cartActions';
function CartScreen() {
const {prodId} = useParams()
const location = useLocation()
const qty = location.search ? Number(location.search.split('=')[1]) : 1
const dispatch = useDispatch()
const cart = useSelector(state => state.cart)
const { cartItems } = cart
useEffect(() => {
if (prodId) {
dispatch(addToCart (prodId, qty))
}
}, [dispatch, prodId, qty])
return(
<div>
Cart
</div>
)
};
export default CartScreen
这里我附加了一个错误的图像
输入图片描述
为什么要删除else语句?当然,如果省略这个逻辑,它将不起作用:D
store.js中的代码看起来很好。请清除本地存储,然后重试。如果你不知道怎么做,删除你的浏览器数据或按照这里的指南。
x是null,所以你不能访问它的product属性。只需在这里使用可选链接或添加if检查即可。这将修复错误:
const existItem = state.cartItems.find(x => x?.product === item.product)
但是不知道为什么项目是空的,也许你应该先弄清楚。
这是修改后的代码,你告诉我,但我有同样的错误。很抱歉打扰你,但我真的没有人可以问。非常感谢你的帮助。
cartReducer.js代码
import { CART_ADD_ITEM } from "../constants/cartConstants"
export const cartReducer = (state = { cartItems: [] }, action) => {
switch (action.type) {
case CART_ADD_ITEM:
const item = action.payload
const existItem = state.cartItems.find(x => {
if(x == null){
return false;
}else{
return x.product === item.product;
}
})
if(existItem){
return{
...state,
cartItems: state.cartItems.map(x =>
x.product === existItem.product ? item:x)
}
}else{
return{
...state,
cartItems:[...state.cartItems, item]
}
}
default:
return state;
}
}
cartScreen.js代码
import React, {useEffect} from 'react'
import { useParams, useLocation } from 'react-router-dom';
import { useDispatch, useSelector} from 'react-redux';
import { Row, Col, ListGroup, Image, Form, Button, Card } from 'react-bootstrap';
import { Message } from '../components/Message';
import { addToCart } from '../actions/cartActions';
function CartScreen() {
const {prodId} = useParams()
const location = useLocation()
const qty = location.search ? Number(location.search.split('=')[1]) : 1
const dispatch = useDispatch()
const cart = useSelector(state => state.cart)
const {cartItems} = cart
console.log('cartItems:', cartItems)
useEffect(() => {
if (prodId) {
dispatch(addToCart (prodId, qty))
}
}, [dispatch, prodId, qty])
return(
<div>
Cart
</div>
)
};
export default CartScreen
当我访问其中一个产品并单击购物车选择数量时,会出现这个
输入图片描述
对于第24行的map
方法也是同样的错误。因此,您所要做的就是添加另一个if语句来检查x是否为空或未定义,就像上面一样。
应该是这样的:
return {
...state,
cartItems: state.cartItems.map(x => {
if (x != null) {
return x.product === existItem.product ? item : x
} else {
return x
}
})
}
或带可选链接:
return{
...state,
cartItems: state.cartItems.map(x => x?.product === existItem.product ? item : x)
}
我仍然想知道为什么你的第一项是空的。可能是您用这个值初始化了存储吗?
我检查了所有的文件,我真的不明白为什么第一个产品是空的
我现在注意到,我放入购物车的任何产品都只识别第一个。据我所知,如果我添加id为3的产品,即控制台中商店的第三个产品,则选择id为1的产品,而不是id为3的产品
输入图片描述
按你说的修改代码
cartReducers.js中的代码
import { CART_ADD_ITEM } from "../constants/cartConstants"
export const cartReducer = (state = { cartItems: [] }, action) => {
switch (action.type) {
case CART_ADD_ITEM:
const item = action.payload
const existItem = state.cartItems.find(x => {
if(x == null){
return false;
}else{
return x.product === item.product;
}
})
if(existItem){
return {
...state,
cartItems: state.cartItems.map(x => {
if (x != null) {
return x.product === existItem.product ? item : x
} else {
return x
}
})
}
}
default:
return state;
}
}
这是store.js
中的代码import { createStore, combineReducers, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
import { productListReducer, productDetailsReducer } from './reducers/productReducers';
import { cartReducer } from './reducers/cartReducers';
const reducer = combineReducers({
productList: productListReducer,
productDetails: productDetailsReducer,
cart: cartReducer,
})
const cartItemsFromStorage = localStorage.getItem('cartItems') ?
JSON.parse(localStorage.getItem('cartItems')) : []
const initialState = {
cart: { cartItems: cartItemsFromStorage }
}
const middleware = [thunk]
const store = createStore (reducer, initialState, composeWithDevTools(applyMiddleware(...middleware)))
export default store