我如何在 React 中承诺链接 redux / sagas dispatch?

How can I promise chain a redux / sagas dispatch in React?

在我的组件中,我有:

export default connect(
  (state) => ({
    autocomplete: state.autocomplete,
    search: state.search,
  }),
  (dispatch) => ({
    onSearch: (location) => (q) => dispatch(actions.push(getUrlWithQS(location, { qs: { q } }))),
    onAutocomplete: (q) => dispatch(actions.autocomplete({ q })),
  }),
  (stateProps, dispatchProps, ownProps) => ({
    ...stateProps,
    ...dispatchProps,
    ...ownProps,
    onSearch: dispatchProps.onSearch(ownProps.location),
  })
)(Home)

我还有:

  doSearch(location) {
    console.log(this.props.onSearch);
    this.props.onSearch(location)
  }

我是否可以做出 onSearch 承诺,这样我就可以知道派送何时完成?

The mental model is that a saga is like a separate thread in your application that's solely responsible for side effects.

redux-saga provides some helper effects wrapping internal functions(takeLatest, takeEvery, etc.) to spawn tasks when some specific actions are dispatched to the Store.

为了处理副作用,redux-saga 允许您分派其他操作来处理错误或成功案例(这是您的承诺行为)。

要在操作后更新您的组件,componentWillReceiveProps(nextProps) 允许您检测状态修改并在之后执行某些操作。

在 saga 异步操作中,您可以使用 putcall 来获得您想要的副作用。

来自 documentation 的相关示例:

import { call, put } from 'redux-saga/effects'

export function* fetchData(action) {
   let url = action.payload.url
   try {
      const data = yield call(Api.fetchUser, url)
      yield put({type: "FETCH_SUCCEEDED", data})
   } catch (error) {
      yield put({type: "FETCH_FAILED", error})
   }
}

要在每个 FETCH_REQUESTED 操作上启动上述任务:

import { takeEvery } from 'redux-saga/effects'

function* watchFetchData() {
  yield takeEvery('FETCH_REQUESTED', fetchData)
}