2017-06-02 4 views
1

私はサガからサンクを派遣しようとすべきではないことを知っています。それはリフィックス・サガがやろうとしていることに反するものです。しかし、私はかなり大きなアプリで作業しており、コードの大部分はサンクで作られています。私たちはビット単位で移行しており、サガの中からサンクをディスパッチする必要があります。サンクは他の部分(約束を返すサンク)で使用されているので変更できません。そのため、多くのことが壊れてしまいます。サガからサンクを発送するには?

configureStore:

const store = createStore(
    rootReducer, 
    initialState, 
    compose(applyMiddleware(thunk, sagaMiddleware)) 
); 

サーガ

// Saga (is called from a takeEvery) 
function* watchWarehouseChange(action) { 
    const companyId = yield select(Auth.id); 

    // We use cookies here instead of localStorage so that we persist 
    // it even when the user logs out. (localStorage clears on logout) 
    yield call(Cookies.set, `warehouse${companyId}`, action.warehouse); 

    // I want to dispatch a thunk here 
    yield put.resolve(syncItems); 
    // put(syncItems) doesn't work either 
} 

サンク:

export function syncItems() { 
    console.log('first!'); 

    return dispatch => { 
    console.log('second!'); 

    return dispatch(fetchFromBackend()).then(
     items => itemsDB.emptyAndFill(items) 
    ) 
    } 
} 

syncItems()が実行されるたびに、唯一first!ログ。 second!は起こりません。

PS:エラーや警告は表示されません。

答えて

3

syncItemsが間違っています。キーは、syncItemsによって返された関数がdispatchに渡される必要があり、syncItemsではないことです。正しい使用方法は、次のようになります。

yield put(syncItems()); 

私は値が(an example gist I put togetherに基づいて)私のブログの記事Idiomatic Redux: Why use action creators?dispatchに渡される方法のいくつかの視覚的な比較を示しました。ここでの例です:あなたのケースでは

// approach 1: define action object in the component 
this.props.dispatch({ 
    type : "EDIT_ITEM_ATTRIBUTES", 
    payload : { 
     item : {itemID, itemType}, 
     newAttributes : newValue, 
    } 
}); 

// approach 2: use an action creator function 
const actionObject = editItemAttributes(itemID, itemType, newAttributes); 
this.props.dispatch(actionObject); 

// approach 3: directly pass result of action creator to dispatch 
this.props.dispatch(editItemAttributes(itemID, itemType, newAttributes)); 

// parallel approach 1: dispatching a thunk action creator 
const innerThunkFunction1 = (dispatch, getState) => { 
    // do useful stuff with dispatch and getState   
}; 
this.props.dispatch(innerThunkFunction1); 

// parallel approach 2: use a thunk action creator to define the function   
const innerThunkFunction = someThunkActionCreator(a, b, c); 
this.props.dispatch(innerThunkFunction); 

// parallel approach 3: dispatch thunk directly without temp variable   
this.props.dispatch(someThunkActionCreator(a, b, c)); 

、あなたの代わりに接続した機器のサガから派遣しているので、ちょうど、this.props.dispatchためyield putを代用。

+0

ありがとう@markerikson、あなたは絶対に正しいです!思ったよりも簡単だった – Mathius17

関連する問題