要求循环,同时要求在axios中存储

问题描述 投票:6回答:1

在一个使用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循环。

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() 需要导入商店,遵循这一系列选项中的第1个选项。

https:/daveceddia.comaccess-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(而不是把它放到每一个失败的传奇行动中)

  2. (可选)派发一个动作,结果是-&gt.送我到 "登录 "界面?

  3. 送我到 "Login "屏幕?

react-native axios redux-saga
1个回答
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);
      }
    );

虽然不完美,但我希望它能对试图实现这一目标的人有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.