【问题标题】:How to handle the loader in a common way(middleware) using RTK Query?如何使用 RTK Query 以通用方式(中间件)处理加载程序?
【发布时间】:2021-10-05 04:00:44
【问题描述】:

我是 RTK 查询的新手,我喜欢使用 RTK 查询。

在我的项目中,我想添加一个通用加载器,如果有任何请求正在运行,则显示页面加载器,一旦响应返回成功或失败,我想隐藏加载器。

如果有人对此有更多背景信息,请告诉我。

提前致谢。

【问题讨论】:

    标签: react-redux loader rtk-query


    【解决方案1】:

    目前,没有开箱即用的实现方式 - 但当然,数据在 Redux 存储中都可用。

    所以你可能可以做类似的事情(伪代码,如果我这里有所有数据结构,请使用 devtools 检查,我现在无法查找)

    const isAnythingLoading = useSelector(state => Object.values(state.api.queries).some(entry => entry.status == 'loading'))
    

    【讨论】:

      【解决方案2】:

      在我的应用程序中,我创建了一个中间件,灵感来自 RTK 查询文档中的 Error Handling 示例:

      const isSilentAction = isAsyncThunkAction(silentAction1, silentAction2, /* other silent actions */);
      
      export const genericLoaderMiddleware = (store) => (next) => (action) => {
          if (!isSilentAction(action)) {
              if (isPending(action)) {
                  store.dispatch(/* show loader action */);
              }
              if (isFulfilled(action) || isRejected(action) || isRejectedWithValue(action)) {
                  store.dispatch(/* hide loader action */);
              }
          }
      
          return next(action);
      };
      

      isSilentAction 基于isAsyncThunkAction macthing 实用程序,该实用程序将createAsyncThunk 创建的操作(如silentAction1silentAction2...等)过滤掉,使其不被中间件按顺序处理在某些情况下不显示加载器。

      应在store.js 中注册自定义中间件:

      export const store = configureStore({
          /*** code omitted for brevity ***/
          middleware: (getDefaultMiddleware) =>
              getDefaultMiddleware()
                  /*** other middleware ***/
                  .concat(genericLoaderMiddleware)
      });
      

      【讨论】:

        猜你喜欢
        • 2021-11-25
        • 2022-08-02
        • 2022-10-07
        • 2022-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多