簡體   English   中英

Redux 中未定義“動作”

[英]'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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM