使用CombineReducer组合我的reducer之后,动作未调度

时间:2020-07-21 06:33:10

标签: javascript reactjs redux react-redux single-page-application

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

我想使用CombineReducer将其拆分为多个文件。但是将其拆分后,redux操作不会调度。

这是我的产品减速器:

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;

我在这里想念什么?

2 个答案:

答案 0 :(得分:4)

您在productReducer上给出了错误的初始状态。 它应该是一个普通的空数组。并且您应该只返回产品数组。而不是整个状态。

'''
def days_in_month(month):
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
return month == 31
    else:
        return 30
'''


'''

    def check_date(date):
    day = int(date[0:2])
    month = int(date[2:4])
    year = date[4:6]
    
    if ( (day<=days_in_month(month)) and (0<month<13) ):
        return True
    else:
        return False
'''    
    
print(check_date('011297'))
                

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

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

答案 1 :(得分:2)

reduceer函数似乎有错误

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;
};