程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何使用React Router V4从axios拦截器重定向?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决如何使用React Router V4从axios拦截器重定向??

开发过程中遇到如何使用React Router V4从axios拦截器重定向?的问题如何解决?下面主要结合日常开发的经验,给出你关于如何使用React Router V4从axios拦截器重定向?的解决方法建议,希望对你解决如何使用React Router V4从axios拦截器重定向?有所启发或帮助;

我通过从Component树之外访问Redux Store并通过注销按钮发送相同的操作来解决了这一问题,因为我的拦截器是在单独的文件中创建的,并且在加载任何Component之前先进行加载。

因此,基本上,@R_595_10673@下工作:

index.Js文件中:

//....lots of imports ommited for brevity
import { createStore, applymIDdleware } from 'redux';
import reduxThunk from 'redux-thunk';
import reducers from './reducers';
import { UNAUTH_USER } from './actions/types'; //this is just a constants file for action types.

const createStoreWithMIDdleware = applymIDdleware(reduxThunk)(createStorE);
const store = createStoreWithMIDdleware(reducers);

//Here is the guy where I set up thE interceptors!
Networkservice.setupInterceptors(storE);

//lots of code ommited again...
//Please pay attention to the "requireAuth" below, we'll talk about it later

ReactDOm.render(
  <ProvIDer store={storE}>
      <browserRouter>
          <div>
              <header />
              <main classname="plan-container">
                  <Switch>
                      <Route exact path="/" component={Landing} />
                      <Route exact path="/login" component={Login} />
                      <Route exact path="/signup" component={Signup} />
                      <Route exact path="/calendar" component={requireAuth(Calendar)} />
                      <Route exact path="/profile" component={requireAuth(ProfilE)} />
                  </Switch>
              </main>
          </div>
      </browserRouter>
  </ProvIDer>
  , document.querySELEctor('.main-container'));

并在network-service.Js文件:

import axios        from 'axios';
import { UNAUTH_USER } from '../actions/types';

export default {
  setupInterceptors: (storE) => {

    // Add a responsE interceptor
    axios.interceptors.response.use(function (responsE) {
        return response;
    }, function (error) {
        //catches if the session ended!
        if ( error.response.data.token.KEY == 'ERR_EXPIRED_TOKEN') {
            console.log("EXPIRED TOKEN!");
            localstorage.clear();
            store.dispatch({ type: UNAUTH_USER });
        }
        return Promise.reject(error);
    });

  }
};

最后但并非最不重要的一点是,我有一个HOC(高阶组件),它将受保护的组件包装在会话结束时进行实际重定向的位置。这样,当我触发动作类型UNAUTH_USER时,它将我的化简器上的isLogged属性设置sessionfalse,因此该组件会随时得到通知并为我进行重定向。

require-auth.Js组件文件:

import React, { Component } from 'react';
import { connect } from 'react-redux';

export default function(ComposedComponent) {

    class requireAuth extends Component {

        componentwillMount() {
            if(!this.props.session.isLogged) {
                this.props.history.push('/login');
            }
        };

        componentwillupdate(nextProps) {
            if(!nextProps.session.isLogged) {
                this.props.history.push('/login');
            }
        };

        render() {
            return <ComposedComponent {...this.props} />
        }
    }

    function mapStatetoProps(statE) {
        return { session: state.session };
    }

    return connect(mapStatetoProps)(requireAuth);
}

希望有帮助!

解决方法

收到403错误时,我想在axios拦截器中进行重定向。但是我如何才能访问React组件之外的历史记录呢?

在React-Router v4中以编程方式导航中,它是在React组件的上下文中,但是这里我在axios上下文中尝试

axios.interceptors.response.use(function (responsE) {
    // Do something with response data
    return response;
  },function (error) {
    // Do something with response error
    if(error.response.status === 403) { console.log("Redirection needed !"); }

    // Trow errr again (may be need for some other catch)
    return Promise.reject(error);
});

大佬总结

以上是大佬教程为你收集整理的如何使用React Router V4从axios拦截器重定向?全部内容,希望文章能够帮你解决如何使用React Router V4从axios拦截器重定向?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。