使用 redux-thunk 取消之前的异步操作

问题描述:

我正在使用 redux-thunk 中间件构建一个 React/Redux 应用程序来创建和处理 Ajax 请求.我有一个经常被触发的特定 thunk,我想在触发新的请求之前取消任何以前启动的 Ajax 请求.这可能吗?

I am building a React/Redux app using the redux-thunk middleware to create and handle Ajax requests. I have a particular thunk that is fired pretty often, and I would like to cancel any previously started Ajax requests before firing a new one. Is this possible?

一种方法是通过为这些请求提供随机 ID 并在处理结果之前检查其状态来将这些请求标记为已取消.

One approach would be to mark those requests as canceled by giving them random id and checking its status before handling the result.

这样做的方法是在您的第一次调度中(在 thunk 中)为该调用分配随机 ID,并在处理结果之前在 reducer 中检查它.

The way to do this is to assign random id for this call in your first dispatch (inside the thunk) and check it in the reducer before handling the result.

const actionId = Math.random();
dispatch({type: AJAX_LOAD_CONST, id:actionId })

当你想取消所有的请求时使用

When you want to cancel all of the request use

dispatch({type:HANDLE_AJAX_RESPONSE, id:actionId, results: json })

当你想处理结果时不要忘记发送你的id

When you want to handle the results don't forget to send the id that you u

在减速器中有这样的东西:

and in the reducer have something like this:

function reducer(state = initialState, action) {
  switch (action.type) {
    case actions.AJAX_LOAD_CONST:
      return Object.assign({}, state, { ajax: state.ajax.concat(action.id) });
    case actions.CANCEL_ALL_AJAX:
      return Object.assign({}, state, { ajax: [] });
    case actions.HANDLE_AJAX_RESPONSE:
      if (state.ajax.includes(action.id) {
        //return state reduced with action.results here
      }
      return state;
  }
}

如果您使用 XMLHttpRequest 或其包装器之一(JQuery?),您还可以存储请求本身并调用 request.abort().如果你使用新的 fetch api,你就没有这种奢侈,因为 promise 没有这种行为.

If you use XMLHttpRequest or one of it's wrappers (JQuery?) you can also store the requests themselves and call request.abort(). if you use the new fetch api you do not have this luxury as promises lack this behavior.