"操作"未在 Redux 中定义



我试图为web商店购物车组件创建一个reducer,但我遇到了这个错误:

未定义"操作">

我的代码如下:

import { CART_ADD_ITEM } from "../constants/cartConstants";
import { addToCart } from '../actions/cartActions';
export const cartReducer = (state = { cartItems: [], action }) => {
switch(action.type){
case CART_ADD_ITEM:
const item = action.payload;
//we check if the item exists in state
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;
}
};

这就是cartActions的样子。它似乎必须以某种方式被以前的代码使用,但如何使用呢?从"axios"导入axios;从".."导入{CART_ADD_ITEM}/constants/cartConstants';

export const addToCart=(id,quantity(=>async(dispatch,getState(=>{const{data}=等待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,
quantity,
}
});
//once dispatched, we wnt ot save an item to local storage added to cart to local storage
//we get it in store.js 
localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems));
}

这是怎么回事?

您的reducer需要一个action作为第二个参数。现在,您的代码将action作为默认状态下的属性,这是不正确的。reducer类型的签名可能是这样的:

export const cartReducer = (state = { cartItems: [] }, action) => {
// Reducer content here
}
reducer将初始状态作为第一个参数,将操作作为第二个参数。

改进的

let initialState = {cartItems: []}
export const cartReducer = (state = initialState, action) => {
switch(action.type){
case CART_ADD_ITEM:
//we check if the item exists in state
const existItem = state.cartItems.find(x => x.product === action.payload.product);

if(existItem){
return {
...state,
cartItems: state.cartItems.map(x => x.product === existItem.product ? action.payload : x),
}
} else {
return {
...state,
cartItems : [...state.cartItems, action.payload],
}
}
default:
return state;
}
};

相关内容

  • 没有找到相关文章

最新更新