【问题标题】:Can I abort a thunk from a dispatched action?我可以中止已调度操作的重击吗?
【发布时间】:2018-03-26 17:32:22
【问题描述】:

在 thunk 开始时,我发送一个“START”操作,然后等待一些异步内容,最后发送一个“SUCCESS”操作。

有时可能会在前一个结束(成功操作)之前再次分派此 thunk,因此我希望拒绝第二个 START 操作,并且 thunk 停止继续执行异步内容和 END 操作。

所以我的方法是检查中间件是否已经分派了已分派的操作(之前的操作与当前的操作相同),但我不知道如何在“nice”中的被拒绝操作之后立即从 thunk 中返回'方式。

目前我从中间件返回 false,需要检查 dispatch 的返回值。

export const doSomething = () => async (dispatch, getState) => {

    if(!dispatch({type: 'START'})) return;

    //...async stuff

    dispatch({type: 'SUCCESS'});
}

有没有一种方法可以从一个点(中间件)控制它?

【问题讨论】:

    标签: javascript redux redux-thunk


    【解决方案1】:

    我假设有一个 reducer 可以根据这些操作(STARTSUCCESS、...)更改存储状态。

    如果是这样,您必须在决定发货前检查商店状态:

    export const doSomething = () => async (dispatch, getState) => {
    
        if (getState().isLoading) return ; // <-- ⚠️ ⚠️ ⚠️
    
        if(!dispatch({type: 'START'})) return;
    
        //...async stuff
    
        dispatch({type: 'SUCCESS'});
    }
    

    假设 reducer 做了如下的事情:

    function (state = {}, action) {
      if (action.type === 'START') {
        return {...state , isLoading: true }; 
      }
    
      if (action.type === 'SUCCESS') {
        return {...state , isLoading: false }; 
      }
      return state;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-31
      • 2021-04-22
      • 2022-12-19
      • 2020-12-12
      • 2011-04-16
      • 1970-01-01
      • 2023-04-04
      • 2012-05-07
      • 1970-01-01
      相关资源
      最近更新 更多