【问题标题】:Require cycle while requiring store in axios需要在 axios 中存储时需要循环
【发布时间】:2019-10-06 04:33:02
【问题描述】:

在使用 redux-saga 架构和 axios 的反应式原生应用程序中,我想拦截 401 请求并调度一个将我发送到登录屏幕的操作。

所以在我的 axios 客户端中,我有:

axiosInstance.interceptors.response.use(
(response) => {
    return response
},
(error) => {

    // token expired
    if (error.response.status === 401) {
        console.log(`401 interceptor error: ${JSON.stringify(error)}`)
        store.dispatch({type: "UNAUTHORIZED_RESPONSE_RECEIVED"})
    }
    return Promise.reject(error)
}
)

现在,虽然这可行,但问题是我有一个需求周期:

Require cycle: redux/store.js -> redux/sagas.js -> redux/project/saga.js -> helpers/projectHelper.js -> helpers/client.js -> redux/store.js

这很明显,但是由于要创建商店,我正在应用 sagaMiddleware,为了定义它,我导入了我的 sagas,我在其中导入了 projectHelper 文件(这是一系列 axios ajax api 调用),我在其中导入客户端,为了能够执行store.dispatch(),需要导入商店,遵循这一系列选项中的第一个选项:

https://daveceddia.com/access-redux-store-outside-react/#option-1-export-the-store

一切正常,但这个警告让我有点担心。

Require cycles are allowed, but can result in uninitialized values. Consider refactoring to remove the need for a cycle.

我的问题是:我怎样才能找到其他(也是有创意的)方法来实现我所需要的,即:

  1. 拦截 401(不将其放入每个失败的 saga 动作中)

  2. (可选)调度一个最终结束的动作 ->

  3. 将我转到“登录”屏幕?

【问题讨论】:

  • 我也有同样的问题。你有没有找到一个创造性的答案?
  • 我找到了一个可能对你有帮助的解决方案,我只是发布了一个答案,以防对其他人有用。

标签: react-native axios redux-saga


【解决方案1】:

对于任何对此用例有问题的人,这是我采用的解决方案。

在我的应用程序主要组件之一(可能是 App.tsx)中,我放置了一个 Axios 拦截器

    componentDidMount() {


    const self = this;
    axios.interceptors.request.use(
      function(config: AxiosRequestConfig) {

       // useful to show a loader
       self.props.loading(true);

        return config;
      },
      function(error) {
        return Promise.reject(error);
      }
    );

    axios.interceptors.response.use(
      function(response) {
        // loader stops
        self.props.loading(false);

        return response;
      },
      function(error) {
        self.props.loading(false);
        if (
          typeof error.response !== "undefined" &&
          error.response.status === 401
        ) {
          console.log(`401 interceptor error: ${JSON.stringify(error)}`);

          NavigationService.navigate("Login", null);
        }
        if (
          typeof error.message !== "undefined" &&
          error.message == "Network Error"
        ) {
          console.log(`Network Error`);
        }
        return Promise.reject(error);
      }
    );

并不完美,但我希望它对试图实现这一目标的人有用!

【讨论】:

    猜你喜欢
    • 2021-05-14
    • 2011-03-24
    • 2013-05-31
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 1970-01-01
    相关资源
    最近更新 更多