首页 文章

Redux:是否有用于跟踪异步请求状态的标准实现或库?

提问于
浏览
4

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 } 这样的东西 .

2 回答

  • 3

    看看这个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;
      }
    
    };
    

    希望可以帮助;)

  • 1

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

相关问题