如何在 React js 应用程序中从 axios 拦截器重定向?

Howto redirect from axios interceptor in reactjs app?

我正在尝试检查每个 axios 请求是否存在 header 路径中的 non-public 令牌。如果找不到令牌,我想将用户带到登录页面。 但这是在 reactjs 应用程序内部。实现这一目标的方法是什么?

axios.interceptors.request.use(function (config) {
 //If the header does not contain the token and the url not public, redirect to login  
 var accessToken = null;
 if(sessionStorage.getItem('currentUserString')){
  accessToken =  'bearer '+JSON.parse(sessionStorage.getItem('currentUserString')).tokenDetails.accessToken;
 }

 var configURL = config.url;
 //if token is found add it to the header
 if (accessToken) {
   if (config.method !== 'OPTIONS') {
          config.headers.authorization = accessToken;
   }
 }
 //otherwise if the request is not for login page/auth service/home redirect to login page
 else if(!isNotOpenPath(config.url)){

   //we may want to store current path in the cookies. This can be retrieved after login is successful
   //WHAT TO DO HERE TO TAKE USER TO LOGIN PAGE IN THE REACT JS APP????
  }    
}

如何向 React 应用发送信号,特别是我们这里没有 dispatch。 我可以只用吗 document.location.href='\login'?

我认为在您的应用程序中使用路由的方法是使用 React Router... 然后导航你可以试试这个...

https://github.com/ReactTraining/react-router/blob/master/docs/guides/NavigatingOutsideOfComponents.md