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

Ste*_*che 11 reactjs redux redux-thunk

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

小智 11

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

执行此操作的方法是在第一次调度(在thunk内)为此调用分配随机ID,并在处理结果之前在reducer中检查它.

const actionId = Math.random();
dispatch({type: AJAX_LOAD_CONST, id:actionId })
Run Code Online (Sandbox Code Playgroud)

当您要取消所有请求时使用

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

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

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

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

如果你使用XMLHttpRequest或其中一个包装器(JQuery?),你也可以自己存储请求并调用request.abort().如果你使用新的fetch api你没有这种奢侈,因为promises缺乏这种行为.


Moh*_*ami 5

如果您使用的是 jquery ajax,您可以让您的动作创建者返回承诺,它将由调度函数返回,然后可以中止它。这是一个例子:

动作创建者

function doSomething() {
  return (dispatch) => {
    return $.ajax(...).done(...).fail(...);
  }
}
Run Code Online (Sandbox Code Playgroud)

您的组件

  componentDidMount(){
    this.previousPromise = this.props.dispatch(doSomething());
  }

  somefnct() {
    this.previousPromise.abort();
  }
Run Code Online (Sandbox Code Playgroud)

  • 你不应该再使用 jQuery。 (2认同)