【问题标题】:ReactJS Handle API error in redux middlewareRedux 中间件中的 ReactJS 处理 API 错误
【发布时间】:2020-12-17 12:51:35
【问题描述】:

我正在寻找的是一种处理 API 错误代码的通用方法。例如:

  • 如果有error.status.code401(in this case the 401 would be unauthorized)。 我想调度某个动作,例如清理 redux 状态,并且用户必须再次登录。
  • 如果有error.status.code404(not found)。我想将用户重定向或推送到某个路线。

这些动作对于每个动作都是相同的行为。


以下函数的问题是它没有可用的调度。我正在寻找一种在 redux 中间件中实现这种行为的方法。老实说,没有太多关于它的信息。

** 我的 API 函数:**

export const fetchApi = (url, config) => {
  return fetch(url, config)
    .then((res) => {
      if (!res.ok) {
          if (res.statusCode === 401) {
              // dispatch an action, not possible dispatch is not avaible
          }
      }
      if (res.ok) {
        return res.text();
      }
    })
    .then((text) => (text.length ? JSON.parse(text) : {}));
};

我正在寻找这个方向:

store.js

import {
  createStore,
  applyMiddleware,
  compose,
} from 'redux';
import thunkMiddleware from 'redux-thunk';
import { persistStore } from 'redux-persist';
import { persistedReducer } from './config';

export default () => {
  const middleware = [thunkMiddleware];
  const middleWareEnhancer = applyMiddleware(
    ...middleware,
    thunk.withExtraArgument({
      apiFetch: (...args) =>
        fetchApi(...args).catch((err) => {
          // general error handling when fetchApi has certain errors
          //  that needs to change something in redux store
          if (err.statusCode === 401) {
            //dispatch clean all data action
            store.dispatch({ type: 'reset' });
            //location.href redirect or reload
          }
          // reject the promise
          return Promise.reject(err);
        }),
    })
  );

  const composeEnhancers =
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

  const store = createStore(
    persistedReducer,
    composeEnhancers(middleWareEnhancer)
  );

  let persistor = persistStore(store);

  return { store, persistor };
};

我只是盲目地寻找可能的解决方案。如果您有任何建议,请随时发表评论。

更新: 当我添加这个中间件时。我可以从动作中收听有效载荷,看看是否有人抛出“未经授权”。基于此,我可以调度一个动作。我不知道这个解决方案有多防水。

更新:

中间件:

const authInterceptor = ({ dispatch }) => (next) => (
  action
) => {
 
  if (action.payload === 'unauthorized') {
    dispatch(something());
  } else {
    next(action);
  }
};

Store.js

export default () => {
  const middleware = [thunkMiddleware, authInterceptor];
  const middleWareEnhancer = applyMiddleware(...middleware);
  const composeEnhancers =
    (true && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) ||
    compose;
  let store = createStore(
    persistedReducer,
    composeEnhancers(middleWareEnhancer)
  );

  let persistor = persistStore(store);

  return { store, persistor };
};

【问题讨论】:

    标签: reactjs api redux middleware http-status-code-401


    【解决方案1】:

    有趣的是,您的问题似乎与 redux-thunk、redux 架构有关。寻找处理 redux 我们应该创建三个主要文件 action 文件、reducers 文件,最后是 store(有些人可能会直接在根文件中写 store,比如 App.js 或 index.js) 任何 redux-thunk 逻辑都必须存在于操作文件中,这样您将 git dispatch 作为传递给您的操作的道具 这是一个例子 如果我们有一个名为 signupUserAsync 的操作来注册我们的用户

    const signupUserAsync = (props) => {
     return (dispatch ) => {
      Api.post(/*whaterever is our URL, pramas, data*/).then(res=> dispatch(saveDataAction(res.data))
     }
    }
    

    有了它,它就会为你工作。 您可以通过此处的文档了解更多信息:https://github.com/reduxjs/redux-thunk

    或者在这种情况下,你可以试试这个 -->

    export const fetchApi = (url, config) => {
      return (dispatch) => {
     fetch(url, config)
        .then((res) => {
          if (!res.ok) {
              if (res.statusCode === 401) {
                  // Now hopefully you will have the dispatch function working
              }
          }
          if (res.ok) {
            return res.text();
          }
        })
        .then((text) => (text.length ? JSON.parse(text) : {}));
     }
    };
    

    【讨论】:

    • 我认为 redux 架构没有问题。这部分工作正常。我有我的 thunk 操作、reducers、选择器等。我正在寻找一种适当的方法来通用处理某些 API 错误。像 401、404、500 等。
    • 好的,我已经编辑了我的答案,请尝试一下,让我知道它是否适合你
    • 这也行不通。因为您在 thunk 操作中调用 fetchApi 函数。所以 thunk 动作: const someThunkAction () => { return (dispatch, getState) => { return fetchApi('/something/url/data', { config object}).then.((res) => dispatch() ).catch((err)=> dispatch())}}。在 fetchApi 函数内部,没有可用于处理 401 或 404 的调度
    猜你喜欢
    • 2018-09-08
    • 2017-08-27
    • 2017-05-16
    • 1970-01-01
    • 2021-04-26
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多