【问题标题】:Redux: Is there any standard implementation or library for keeping track of the status of an async request?Redux:是否有任何标准实现或库来跟踪异步请求的状态?
【发布时间】:2017-02-15 12:40:45
【问题描述】:

redux async actions in the docs 中,异步请求的状态作为属性isFetching 保存在各种对象的状态容器中:

{
  selectedSubreddit: 'frontend',
  postsBySubreddit: {
    frontend: {
      isFetching: true,
      didInvalidate: false,
      items: []
    },
    reactjs: {
      isFetching: false,
      ...

这很好,但是我正在寻找构建我的应用程序,并且我正在寻找可以跨多个对象扩展的设计模式,这些对象必须保存在我的状态容器中并与我的 api 同步。所以我正在寻找 redux 社区采用的标准或库。

我发现Flux Standard Action 看起来很合理,但这更像是如何处理有效负载和错误的标准化,不是异步请求的状态。

是否有很多 redux 开发人员正在使用的库或模式?我认为可能会有类似{ success, isFetching, error }.

【问题讨论】:

  • 我创建了一个函数,当被调用时会产生一个具有以下结构的 reducer:{ inProgress, succeeded, failed, failureReason }。该函数将映射到“进行中”、“成功”和“失败”事件的操作名称作为参数。如果你愿意的话,有点像高阶减速器。便于重复使用。

标签: reactjs redux flux reactjs-flux


【解决方案1】:

看看这个library,随心所欲地使用它。

在我的应用程序中,我曾这样使用它,首先将其添加到商店配置中的中间件中。在此之后,您将您的操作设置为承诺,并且有效负载是承诺。

export const reqAllGames = games => {

  const promise = new Promise((resolve, reject) => {
    request
      .get(`${config.ROOT_URL}/${config.API_KEY}`)
      .end((err, res) => {
        if (err) {
          reject(err);
        } else {
          resolve(res.body.top);
        }
      });
  });

  return {
    type:    types.RECEIVE_ALL_GAMES,
    payload: promise
  };

};

在你可以设置你的减速器之后:

const gameReducer = (games = { isFetched: false }, action) => {

  switch (action.type) {
    case `${types.RECEIVE_ALL_GAMES}_PENDING`:
      return {};
    case `${types.RECEIVE_ALL_GAMES}_FULFILLED`:
      return {
        games:     action.payload,
        err:       null,
        isFetched: true
      };
    case `${types.RECEIVE_ALL_GAMES}_REJECTED`:
      return {
        games:     null,
        err:       action.payload,
        isFetched: true
      };
    default:
      return games;
  }

};

希望能有所帮助;)

【讨论】:

  • 我将尝试Flux Standard Action Redux Promise,但我会将这个问题标记为已接受,因为它引入了在操作中使用承诺来管理异步状态。感谢 EQuimper
【解决方案2】:

是的,Redux 有各种各样的插件,其中许多与异步行为有关。我的Redux addons catalog 几乎列出了所有这些。有middlewares for handling async behaviorutilities to generate actions describing async workprebuilt libs to track request status 等等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 2021-04-02
    • 2023-04-06
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多