redux 还原型:存储区没有有效的reducer,请确保传递给combineReducers的参数是其值为reducer的对象

8aqjt8rx  于 2023-02-04  发布在  其他
关注(0)|答案(1)|浏览(109)

错误类型:存储区没有有效的reducer。请确保传递给combineReducers的参数是其值为reducer的对象。
我正在尝试添加应用商店,但我的应用出现故障。我不知道错误来自何处。有人能指出我的错误以及如何修复吗?
贮藏

import { configureStore } from '@reduxjs/toolkit';
import rootReducers from './reducers';

const store = configureStore({
  reducer: rootReducers,
});

export default store;

还原剂
x一个一个一个一个x一个一个二个x

thigvfpy

thigvfpy1#

我在handleCart reducer函数代码中只看到几个明显的问题,可能是引发异常的原因。handleCart reducer函数在默认情况下似乎缺少返回状态。REMOVEITEM情况还错误地假定已定义exist,并访问可能未定义的对象的qty属性。请记住,当在数组中找不到匹配元素时,Array.prototype.find将返回undefined
确保默认导出handleCart,以便可以将其导入以创建根缩减器。

const cart = [];

const handleCart = (state = cart, action) => {
  const product = action.payload;

  switch (action.type) {
    case ADDITEM: {
      // Check product exist
      const exist = state.find(x => x.id === product.id);

      if (exist) {
        return state.map(x =>
          x.id === product.id ? { ...x, qty: x.qty + 1 } : x,
        );
      }
      return [...state, { ...product, qty: 1 }];
    }

    case REMOVEITEM: {
      const exist = state.find(x => x.id === product.id);

      if (exist) {
        // item exists, update quantity
        if (exist.qty === 1) {
          return state.filter(x => x.id !== exist1.id);
        } else {
          return state.map(x =>
            x.id === product.id ? { ...x, qty: x.qty - 1 } : x,
          );
        }
      }
      // item didn't exist, just return current state
      return state;
    }

    default:
      // No action to do, return current state
      return state;
  }
};

export default handleCart;

你正在使用redux-toolkit,为什么不创建状态切片?这里有一个类似的使用createSlice的实现。这允许你使用可变更新来编写reducer函数,而不需要浅拷贝状态的所有部分。

import { createSlice } from '@reduxjs/toolkit';

const initialState = [];

const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addItem: (state, action) => {
      const product = state.find(product => product.id === action.payload.id);

      if (product) {
        product.qty++;
      } else {
        state.push({ ...action.payload, qty: 1 });
      }
    },
    removeItem: (state, action) => {
      const product = state.find(product => product.id === action.payload.id);

      if (product) {
        product.qty--;
        if (product.qty === 0) {
          state.filter(product => product.id !== action.payload.id);
        }
      }
    },
  },
});

export const { addItem, removeItem } = cartSlice.actions;

export default cartSlice.reducer;

相关问题