首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从函数重定向React路由器

从函数重定向React路由器
EN

Stack Overflow用户
提问于 2018-01-18 20:33:14
回答 2查看 1.5K关注 0票数 3

我正在使用create- React -app,react-redux,react-thunk,react-router创建一个react应用程序。

我在认证后设置了一个本地存储变量"current_user“,这样我就可以设置我的受限路由器了。

我使用Axios发出ajax请求,并且在我的初始index.js文件中设置了一个全局Axios拦截器,以便如果任何ajax调用返回401,它将自动清除本地存储"current_user“。我希望它也能重定向到/Login。

我可以用老式的方法(即window.location)来做这件事,但是,有没有办法将这个全局函数设置为从应用程序中的任何位置重定向到登录页面?

全局拦截器:

index.js

代码语言:javascript
复制
import "materialize-css/dist/css/materialize.min.css";
import "jquery/dist/jquery.min.js";
import "materialize-css/dist/js/materialize.min.js";
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import reduxThunk from 'redux-thunk';
import axios from "axios";

import App from "./components/App";
import reducers from './reducers';

const store = createStore(reducers, {}, applyMiddleware(reduxThunk));

axios.interceptors.response.use(undefined, function (error) {
  if(error.response.status === 401) {    //Setup Global Config
    localStorage.setItem('current_user', null);
   //Would like to redirect to /Login here
  }
});

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.querySelector("#root")
);
EN

回答 2

Stack Overflow用户

发布于 2018-01-18 20:43:25

您可以尝试如下所示:

代码语言:javascript
复制
import createHistory from 'history/createBrowserHistory';


const history = createHistory({
 window.location.pathname,
});

// ...

if(error.response.status === 401) {
   // ...
   history.push('/login');
}

如果在localStorage:https://github.com/strapi/strapi-examples/blob/master/login-react/react-login-front-end-app/app/containers/WithAuth/index.js中没有令牌,您可以在此处找到另一种方法来重定向您的用户

票数 0
EN

Stack Overflow用户

发布于 2018-06-24 23:26:02

只需使用:return <Redirect to="/login" />。这应该可以了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48321489

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档