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

问题描述 投票:3回答:2

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

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:我没有收到任何错误或警告。

javascript reactjs redux redux-thunk redux-saga
2个回答
6
投票

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

yield put(syncItems());

我在我的博客dispatch(基于Idiomatic Redux: Why use action creators?)中展示了如何将值传递到an example gist I put together的视觉比较。以下是示例:

// 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));

在你的情况下,只需用yield put替换this.props.dispatch,因为你是从一个传奇而不是一个连通的组件派遣的。


0
投票

使用https://github.com/czewail/bind-promise-to-dispatch

在saga函数中添加resolve和reject参数

然后使用这个包func wrap this.props.dispatch

那么你可以将它与诺言一起使用

© www.soinside.com 2019 - 2024. All rights reserved.