reactjs - 我如何保证在 React 中链接 redux/saga 调度?

标签 reactjs redux redux-saga

在我的组件中,我有:

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 promise ,以便我知道调度何时完成?

最佳答案

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 允许您分派(dispatch)其他操作来处理错误或成功案例(这是您的 promise 类似行为)。

要在操作后更新组件,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)
}

关于reactjs - 我如何保证在 React 中链接 redux/saga 调度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41753871/

相关文章:

reactjs - 当多个请求发出时如何处理刷新 token ?

javascript - 如何解决实际需要 componentWillMount 的用例?

performance - React Native 与 Redux 的低性能

redux-saga - 启用 addEventListener 回调来执行 put

javascript - 您可以调用一个 saga 并仅在另一个 saga 完成时继续执行吗?

javascript - react : show object as working JS format?

reactjs - 在 React-Native 的 ListView 末尾显示事件指示器

javascript - react & 归零 : connect() to multiple components & best practices

javascript - 一键从 redux 存储中添加/删除对象

react-native - React Navigation V5 + Redux Saga : How can I navigate from the Saga?