[英]'action' is not defined in Redux
我尝试为 web 商店购物车组件创建一个减速器,但我遇到了这个错误:
“动作”未定义
我的代码如下:
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; 从'../constants/cartConstants'导入{ CART_ADD_ITEM };
export const addToCart = (id, quantity) => 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,
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
作为第二个参数。 现在,您的代码在默认 state 中包含作为属性的action
,这是不正确的。 reducer 类型签名应该是这样的:
export const cartReducer = (state = { cartItems: [] }, action) => {
// Reducer content here
}
reducer 将初始 state 作为第一个参数,将 action 作为第二个参数。
改进
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;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.