redux预加载状态不确定与组合形式
我正在使用redux,并且有以下代码:
const initialState = {
foo: "foo",
};
const store = createStore(
rootReducer,
initialState
);
...
const rootReducer = combineReducers({,
foo: (state) => {
console.log(state);
return state;
},
});
根据文档:
使用Comminereducer()行为更加细微。那些在预加载中指定状态的还原器将获得该状态。其他还原器将收到未定义的,因此,将返回到状态= ...他们指定的默认参数。
我期望我的情况是前者,因此我希望我的还原器能够将记录到控制台上,但是我得到了
undefined
,然后,这会导致应用程序失败为“键“ foo”在初始化期间返回未定义的“切片减少”。我想念什么?
顺便说一下,我知道我可以在foooreducer
中设置一个默认值来处理这种情况(即Set set (state = someinitialState)
),但我的问题是:被迫这样做?因为根据文档,我不应该这样。
编辑
这是一个问题的工作示例:
const rootReducer = Redux.combineReducers({
foo: (state) => {
console.log(`State is: ${state}`);
return state;
}
});
const initialState = {
foo: 'initialFooValue',
};
try {
const store = Redux.createStore(rootReducer, initialState);
} catch (error) {
console.error(error);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.2.0/redux.js"></script>
I am using Redux and I have the following piece of code:
const initialState = {
foo: "foo",
};
const store = createStore(
rootReducer,
initialState
);
...
const rootReducer = combineReducers({,
foo: (state) => {
console.log(state);
return state;
},
});
According to the documentation:
With combineReducers() the behavior is more nuanced. Those reducers whose state is specified in preloadedState will receive that state. Other reducers will receive undefined and because of that will fall back to the state = ... default argument they specify.
And I'm expecting my case to be the former, hence I'm expecting my reducer to log "foo"
to the console, but I'm getting undefined
instead, which is then causing the application to fail as "the slice reducer for key "foo" returned undefined during initialization". What am I missing?
By the way, I know I can set a default value in my fooReducer
to handle this case (i.e. set (state = someInitialState)
), but my question is: am I forced to do so? Because according to the documentation I shouldn't be.
Edit
Here's a working example of the issue:
const rootReducer = Redux.combineReducers({
foo: (state) => {
console.log(`State is: ${state}`);
return state;
}
});
const initialState = {
foo: 'initialFooValue',
};
try {
const store = Redux.createStore(rootReducer, initialState);
} catch (error) {
console.error(error);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.2.0/redux.js"></script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜您在这里缺少的是,每个还原器都需要自己的
初始值
当您使用comminereducers
时,请检查此代码以查看我的意思:I guess what you're missing here is the fact that each reducer needs its own
initial value
when you're usingcombineReducers
, Check This code to see what I mean: