我正在运行一个简单的Redux reducer和store,但由于某种原因,默认情况下会调用reducer.这是正常的吗?
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" });
Run Code Online (Sandbox Code Playgroud)
上面的代码段输出:
"default"
"hello"
Run Code Online (Sandbox Code Playgroud)
我只是希望它能够记录hello,为什么default呢?这是一个JSBin.
Redux在创建存储时在内部调度虚拟动作以设置初始状态.根据Redux文档:
创建存储时,Redux会向您的reducer发送一个虚拟操作,以使用初始状态填充存储.您并不打算直接处理虚拟动作.请记住,如果作为第一个参数赋予它的状态是未定义的,那么你的reducer应该返回某种初始状态,并且你们都已经设置好了.
因此,当您首次调用 reducer时,state将不确定,因此{}将使用您的默认值.此外,它会转到这种default情况,因为你不应该明确地处理动作,因此你得到了console.log.确保返回default案例中的状态以正确设置初始状态.
出于好奇,Redux所做的第一个虚拟调用的动作类型"@@redux/INIT"表示Redux正在初始化商店并对其进行测试.类似的事情发生combineReducers在测试Reducer中的坏模式.具体来说,在源头:
Run Code Online (Sandbox Code Playgroud)// 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 })
因此,初始调度基本上为每个reducer提供其各自的状态切片,并填充初始状态树.
| 归档时间: |
|
| 查看次数: |
453 次 |
| 最近记录: |