使用 combineReducer 组合我的 reducer 后,操作未调度

After combining my reducer using combineReducer, action is not dispatching

这是我的减速器文件。如果我使用它,一切正常。 https://gist.github.com/ashiqdev/9129d43c4397ff752f88739cc1f4309f

我想使用 combineReducer 将它拆分成多个文件。但是拆分之后,redux action 没有调度。

这是我的产品减速器:

import { SET_PRODUCTS } from '../actionTypes';

const init = {
  products: [],
  keyword: '',
  cartItems: {},
};

const productReducer = (state = init, action) => {
  if (action.type === SET_PRODUCTS) {
    return {
      ...state,
      products: action.payload,
    };
  }
  return state;
};

export default productReducer;

我在这里合并它:

import { combineReducers } from 'redux';

import productReducer from './productReducer';
import cartItemReducer from './cartItemReducer';
import keywordReducer from './keyWordReducer';

const reducers = combineReducers({
  products: productReducer,
  keyword: keywordReducer,
  cartItems: cartItemReducer,
});

export default reducers;

我在这里缺少什么?

好像是reducer函数出错了

const productReducer = (state = init, action) => {
  if (action.type === SET_PRODUCTS) {
    // here you have to return the new state for `state.products` and not for `state`
    return {
      ...state,
      products: action.payload,
    };
  }
  return state;
};

改用这个减速器

const productReducer = (state = [], action) => {
  if (action.type === SET_PRODUCTS) {
    return [...action.payload];
  }
  return state;
};

您在 productReducer 上给出了错误的初始状态。 它应该是一个普通的空数组。你应该 return 只有产品数组..而不是整个州。

const productReducer = (state = [], { type, payload }) => {
  if (type === SET_PRODUCTS) {
    return [...payload]
  }
  return state;
};

或者如果您不想更改 productReducer,则必须使用 store.products.products.

使用商店变量

const products = useSelector((state) => state.products.products)