問題: をthunk
導入する前にミドルウェアを使用すると、サンクRedux.combineReducers
にgetState
渡された は正しいキーを持つオブジェクトを正しく返します。Redux.combineReducers
useにリファクタリングした後getState
、サンクに渡された は、ネストされたキーを持つオブジェクトを返すようになりました。以下のコードを参照してください。これは (うまくいけば) 私の要点を示しています。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);