问题:在引入 之前使用thunk
中间件时Redux.combineReducers
,getState
传递给 thunk 的正确返回具有正确键的对象。在重构为 use 之后Redux.combineReducers
,getState
传递给 thunk 现在返回一个带有嵌套键的对象。请参阅下面的代码(希望)说明我的观点。这可能导致潜在的维护噩梦,即必须不断为任何thunk
访问状态的方法获取正确的密钥。
问题:有没有一种简单的方法可以在 ? 中设置正确的上下文键thunk
?当我结合减速器并且必须插入键来访问正确的状态时,代码感觉很脆弱。我错过了一些简单的东西吗?
代码前:
const Redux = require('redux'),
Thunk = require('redux-thunk');
// this is an action generator that returns a function and is handled by thunk
const doSomethingWithFoo = function() {
return function(dispatch, getState) {
// here we're trying to get state.fooValue
const fooValue = getState().fooValue;
dispatch({ type: "DO_SOMETHING", fooValue });
}
};
// this is a simple action generator that returns a plain action object
const doSimpleAction = function(value) {
// we simply pass the value to the action.
// we don't have to worry about the state's context at all.
// combineReducers() handles setting the context for us.
return { type: "SIMPLE_ACTION", value };
}
const fooReducer(state, action) {
// this code doesn't really matter
...
}
const applyMiddleware = Redux.applyMiddleware(Thunk)(Redux.createStore);
const fooStore = applyMiddleware(fooReducer);
代码后(引入更全球化的 appStore):
// need to rewrite my thunk now because getState returns different state shape
const doSomethingWithFoo = function() {
return function(dispatch, getState) {
// here we're trying to get state.fooValue, but the shape is different
const fooValue = getState().foo.fooValue;
dispatch({ type: "DO_SOMETHING", fooValue });
}
};
const appReducers = Redux.combineReducers({
foo: fooReducer,
bar: barReducer,
});
const appStore = applyMiddleware(appReducers);