在初始化期间,React/Redux reducer返回undefined

Ran*_*tes 5 javascript reactjs redux react-redux

我正在研究我的第一个React/Redux项目.一切都很顺利,然后我尝试创造一个新的减速机.我认为这是一个非常简单的,但是当我加载页面时,我收到一个错误"Reducer X在初始化期间返回undefined".跟踪说这发生在combineReducers()中.我发现了几个类似的问题,但他们没有解决问题.

在这个问题上:尽管为initialStore()提供了initialState,为什么我在初始化期间得到"Reducer [...]返回未定义"?

问题是他们在createStore()中使用了initialState,我没有这样做.

在这个问题上:为什么我的Redux减速器认为我的状态未定义?

问题是reducer中缺少默认返回值,我有.

我的减速机代码如下.我在开头有一个console.log(),根本没有被调用.

减速器/ reducer_which_sorter.js

import { SORT_CAMPERS } from '../actions/index';

export default function(state = null, action) {
    console.log("action is", action);
    switch(action.which) {
        case 'recent':
        case 'alltime':
            return action.which;
            break;
        default:
            return state;
    }

    return state;
}
Run Code Online (Sandbox Code Playgroud)

减速器/ index.js

import { combineReducers } from 'redux';
import Campers from './reducer_camper_list';
import ActiveSorter from './reducer_which_sorter';

const rootReducer = combineReducers({
  campers: Campers,
  activeSorter: ActiveSorter
});

export default rootReducer;
Run Code Online (Sandbox Code Playgroud)

一切都很好.webpack没有错误.我有双倍,三倍和四倍检查我的文件路径.我没有看到任何拼写错误.谁能看到我在这里失踪的东西?

Rad*_*io- 5

Redux 要求是type在操作上使用属性,而不是which像您在示例中所做的那样。由于未调用您的 console.log 检查,问题可能出在您的其他减速器中(未显示在您的问题中。)

这很重要的原因是combineReducers使用特殊的 INIT 操作类型调用您的 reducer 函数:

const initialState = reducer(undefined, { type: ActionTypes.INIT })
Run Code Online (Sandbox Code Playgroud)

来源:https : //github.com/reactjs/redux/blob/master/src/combineReducers.js

您的函数,因为它打开 'action.which' 而不是 'action.type',除了未定义之外,无法返回任何内容。