【问题标题】:Resolving async function in action creator解析动作创建器中的异步功能
【发布时间】:2018-02-06 02:18:24
【问题描述】:

我正在尝试在状态更新之前在我的操作创建器中解决此异步调用。我试图实现 redux thunk,但我对它和 angular4+ 整体来说还很陌生。

这是我的动作创建者的样子:

@Injectable() 
export class IndexActions {
  constructor(
    private _cloudReadService: CloudReadService
  ) {}
  static UPDATE_INDEX = 'UPDATE_INDEX';

  updateIndex(): ActionWithPayload {
    return {
      type: IndexActions.UPDATE_INDEX,
      payload: this._cloudReadService.getRecordsByOwner()
        .then(response => {return response})
        .catch(err => console.log)
    }
  }
}

thunk 的主要问题是我的服务方法没有在实际的 thunk 中定义。

这是服务的基本外观:

@Injectable()
export class CloudReadService {
  constructor() {
  }

  getRecordsByOwner(): any {
    return firebase.database()
      .ref('lists/records/owners')
      .orderByChild('ownerName')
      .once('value')
      .then(snapshot => {
          /* process response */
          return processedResponse;
      }
    })
  }
}

我想我的问题真的是如何在 redux 中间件中使用服务方法,或者有其他方法吗?

非常感谢任何帮助。

【问题讨论】:

    标签: angular asynchronous redux thunk


    【解决方案1】:

    一种方法是分派三个单独的操作。

    thunk 中间件添加到您的商店将允许您从您的操作返回一个带有分派参数的函数,以便您可以分派多个操作。

    import thunkMiddlware from 'redux-thunk';
    
    const store = createStore(
      // reducer
      rootReducer,
      // preloadedState
      undefined,
      // compose simply enables us to apply several store enhancers
      // Right now, we are only using applyMiddlware, so this is
      // just future-proofing our application
      compose(
        // Middlware can intercept dispatched actions before they reach the reducer
        // in order to modify it in some way
        applyMiddleware(
          // Thunk allows functions to be returned from action creators
          // so we can do things like dispatch multiple actions in a 
          // single action creator for async actions
          thunkMiddlware
        )
      )
    );
    

    然后您可以通过仅调用 updateIndex() 来适当地分派请求的每个阶段

    updateIndexStart(): Action {
     return {
       type: 'UPDATE_INDEX_START'
     };
    }
    
    updateIndexSuccess(response): ActionWithPayload  {
     return {
       type: 'UPDATE_INDEX_SUCCESS',
       payload: response
     };
    }
    
    updateIndexError(err): ActionWithPayload  {
     return {
       type: 'UPDATE_INDEX_ERROR',
       payload: err
     };
    }
    
    updateIndex() {
      return (dispatch) => {
        dispatch(updateIndexStart());
        cloudReadService.getRecordsByOwner()
          .then(response => dispatch(updateIndexSuccess(response)))
          .catch(err => dispatch(updateIndexError(err)));
      };
    }
    

    【讨论】:

    • 我以为我以前尝试过类似的方法,但没有成功。这一次做到了!我不得不改变一些事情。我必须调度成功和错误函数,并在他们的调用前加上“this”。
    猜你喜欢
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    相关资源
    最近更新 更多