开发者问题收集

Redux 中未定义“action”

2021-05-22
996

我尝试为网络商店购物车组件创建一个 Reducer,但遇到了此错误:

'action' is not defined

我的代码如下:

 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 就是这样的。似乎它必须以某种方式被前面的代码使用,但如何使用呢? import axios from 'axios'; import { CART_ADD_ITEM } from '../constants/cartConstants';

export const addToCart = (id, quantile) => 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));
 }

这有什么问题?

2个回答

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

export const cartReducer = (state = { cartItems: [] }, action) => {
  // Reducer content here
}
Nick
2021-05-22

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;
}
 };
akhtarvahid
2021-05-22