这实际上是一个相当晦涩的问题。究其原因是因为,每the Redux documentation on createStore
:
When a store is created, Redux dispatches a dummy action to your reducer to populate the store with the initial state. You are not meant to handle the dummy action directly. Just remember that your reducer should return some kind of initial state if the state given to it as the first argument is undefined, and you're all set.
而且通过文档提到的只是让这个假动作恰好be this line the source:
dispatch({ type: ActionTypes.INIT })
这里,ActionTypes.INIT
基本上是跟着一个随机字符串,字符串@@redux/INIT
数字和句点。
因此,当你与createStore
创建存储,虚拟动作被分派到你的减速,和动作类型在reducers
对象不存在,所以你得到的错误,undefined是不是一个函数。这就是为什么你总是有你的减速机默认情况下。例如,与switch语句,你总是返回状态的默认情况下:
switch(action.type) {
…
default:
return state;
}
默认情况下允许的动作捕捉如终极版本身派出诱敌动作。同样的原则也适用于你的代码:
export default (state = initialState, action) => reducers[action.type] ? reducers[action.type](state)(action.payload) : state;
这种检查是否减速的reducers
对象实际存在。如果是这样,它会调用减速器。如果不是,就像在默认情况下一样,只是返回状态。
看起来它可以基于显示的内容工作。在发生错误的地方记录'redurs'的值是多少? – bazzells
@bazzells Nope,Redux在商店创建时分派一个虚拟动作,OP不处理错误。查看我的答案了解更多详情。 – Li357