2016-06-16 27 views
1

我正在使用redux-loop從我的reducer中調用動作創建者。這通常很好。在thunk動作創建器中使用redux-loop

但是,我也爲我的一些動作創作者使用了thunk。如果我將常規動作創建者轉換爲thunk,則它在redux-loop中不再可用。

有沒有一種方法可以在reducer中調用redux-loop中的thunk?

回答

0

我建議您在install之前通過applyMiddleware加強版。

createStore(reducer, initialState, compose(
    applyMiddleware(thunk), 
    install() 
)); 

applyMiddelware將捕捉傳遞給store.dispatch()前Redux的循環試圖派遣他們的行動。現在,爲了下一個版本的redux-loop,我打算在應用自己的修改之前讓install()接受商店的其他增強器,以便最終不會成爲問題。

+0

如果你想這不起作用從行動中調度thunk,因爲傳遞給它們的調度行爲還沒有通過thunk中間件增強。我不得不求助於編寫自己的'loopWithThunk'中間件來解決這個問題。 – denisw

0

我沒有將redux-loop和redux-thunk按原樣結合在一起。問題是,如果你先調用applyMiddleware(thunk),然後再調用redux-loop的install(),那麼由thunks調度的動作將不會評估它們的效果(因爲由中間件傳遞給thunk的dispatch還沒有被redux-loop增強)。而如果將兩者交換,效果將無法分配thunk(因爲012xredux-loop使用的效果的版本未通過thunk中間件增強)。

要解決這個問題,我需要寫出下面的漂亮哈克店增強劑:

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) 
相關問題