【发布时间】:2016-10-18 13:31:36
【问题描述】:
我正在使用 redux-loop 从我的 reducer 调用动作创建者。这正常工作。
不过,我也在为我的一些动作创建者使用 thunk。如果我采用常规动作创建器并将其转换为 thunk,则它不再可用于 redux-loop。
有没有办法从 reducer 中的 redux-loop 调用 thunk?
【问题讨论】:
标签: redux redux-thunk
我正在使用 redux-loop 从我的 reducer 调用动作创建者。这正常工作。
不过,我也在为我的一些动作创建者使用 thunk。如果我采用常规动作创建器并将其转换为 thunk,则它不再可用于 redux-loop。
有没有办法从 reducer 中的 redux-loop 调用 thunk?
【问题讨论】:
标签: redux redux-thunk
我建议您在增强器中将 applyMiddleware 传递到 install 之前。
createStore(reducer, initialState, compose(
applyMiddleware(thunk),
install()
));
applyMiddelware 将在 redux-loop 尝试调度它们之前捕获传递给 store.dispatch() 的操作。现在,对于下一个版本的 redux-loop,我计划让 install() 在应用自己的修改之前接受商店的其他增强器,这样这最终不会成为问题。
【讨论】:
loopWithThunk 中间件来解决这个问题。
我没有按原样组合 redux-loop 和 redux-thunk。问题是,如果你先调用applyMiddleware(thunk),然后再调用redux-loop 的install(),thunk 调度的动作将不会评估其效果(因为中间件传递给thunk 的dispatch 不会被redux-增强-循环);而如果将两者互换,效果将无法调度 thunk(因为 dispatch redux-loop 用于效果的版本没有通过 thunk 中间件增强)。
为了解决这个问题,我需要编写以下非常 hacky 的商店增强器:
import { applyMiddleware, compose } from 'redux'
import { install } from 'redux-loop'
export default function loopWithThunk(createStore) {
let enhancedStore
const storeSaver = (createStore) => (reducer, initialState) => {
enhancedStore = createStore(reducer, initialState)
return enhancedStore
}
const thunkMiddleware = () => next => action => {
return (typeof action === 'function')
? action(enhancedStore.dispatch, enhancedStore.getState)
: next(action)
}
return compose(
storeSaver,
install(),
applyMiddleware(thunkMiddleware)
)(createStore)
}
你可以这样使用它:
const store = createStore(reducer, loopWithThunk)
【讨论】: