如何从传奇中派遣一个thunk?

Mat*_*s17 4 javascript reactjs redux redux-thunk redux-saga

我知道我不应该试图从传奇中发出雷鸣声,这与redux-saga试图做的事情背道而驰.但是我在一个相当大的应用程序中工作,大部分代码都是用thunk开发的,我们正在逐位迁移,需要从一个传奇内部发送一个thunk.thunk无法更改,因为它被用在其他部分(一个返回一个promise的thunk),所以它会打破很多东西.

configureStore:

const store = createStore(
  rootReducer,
  initialState,
  compose(applyMiddleware(thunk, sagaMiddleware))
);
Run Code Online (Sandbox Code Playgroud)

佐贺:

// 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
}
Run Code Online (Sandbox Code Playgroud)

咚:

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

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

    return dispatch(fetchFromBackend()).then(
      items => itemsDB.emptyAndFill(items)
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

每当syncItems()执行时,只有first!日志.second!永远不会发生

PS:我没有收到任何错误或警告.

mar*_*son 6

syncItems错了.关键是返回syncItems函数需要传递给它dispatch,而不是syncItems它本身.正确的用法是:

yield put(syncItems());
Run Code Online (Sandbox Code Playgroud)

dispatch在我的博客文章Idiomatic Redux中展示了如何传递价值的视觉比较:为什么要使用动作创作者?(基于我放在一起的一个例子).以下是示例:

// 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));
Run Code Online (Sandbox Code Playgroud)

在你的情况,刚刚替补yield putthis.props.dispatch,因为你是从传奇,而不是连接的组件调度.