需要循环同时需要在 axios 中存储

sup*_*ndr 8 react-native redux-saga axios

在使用 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)
}
)
Run Code Online (Sandbox Code Playgroud)

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

Require cycle: redux/store.js -> redux/sagas.js -> redux/project/saga.js -> helpers/projectHelper.js -> helpers/client.js -> redux/store.js
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)

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

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

  2. (可选)调度一个动作,它结束 ->

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

sup*_*ndr 0

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

在我的应用程序主要组件之一(可能是 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);
      }
    );
Run Code Online (Sandbox Code Playgroud)

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