为什么Reduux在Redux中默认称为默认值?
我正在运行一个简单的Redux reducer和存储,但由于某种原因,reducer被默认调用。这是正常的吗?为什么Reduux在Redux中默认称为默认值?
const apiWrapper = (state = {}, action) => {
switch(action.type) {
case "HELLO":
console.log("hello");
return state;
break;
default:
console.log("default");
}
}
const { createStore } = Redux;
const store = createStore(apiWrapper);
store.dispatch({ type: "HELLO" });
以上输出的代码片段:
"default"
"hello"
我只希望它登录hello
,为什么default
有太多?这是一个JSBin。
Redux在创建存储时为了设置初始状态而在内部分派虚拟操作。根据Redux documentation:
当创建一个存储时,Redux会为您的reducer分派一个虚拟动作以使用初始状态填充存储。你并不是想直接处理虚拟行为。只要记住,如果给定的状态作为第一个参数是未定义的,那么你的reducer应该返回某种初始状态,并且你已经设置好了。
因此,当你减速首次调用,state
将因此未定义默认值{}
将被使用。此外,它将转到default
的情况,因为您不应该明确处理该操作,因此您将获得console.log
。确保返回default
案例中的状态以正确设置初始状态。
只是出于好奇,动作类型的第一个哑呼叫终极版确实是"@@redux/INIT"
这标志着终极版正在初始化存储和测试它。类似的事情发生在combineReducers
以测试reducer中的不良模式。具体而言,在the source:
// When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT })
因此,最初的调度基本上给出了每个减速机各自的状态的片,并填充初始状态树。
霍莉莫莉!我想你只是给了我需要的精神“点击”,以充分理解减少和初始状态! – user123
@ user123没问题,很高兴我能帮忙! – Li357
是的,来自@Andrew Li的优秀回答。您可能还想阅读文档中的[Structuring Reducers - Initializing State](http://redux.js.org/docs/recipes/reducers/InitializingState.html)部分,它解释了'preloadedState' createStore()'的参数,reducer的默认值和'combineReducers()'效用函数。 – markerikson
您可以只记录'action' ... –
获取Chrome的'Redux'插件,您实际上可以遍历该状态并查看触发的所有操作以及每个步骤的状态。 – samanime
伟大的建议,谢谢@samanime – user123