我正在使用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
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")
);发布于 2018-01-18 20:43:25
您可以尝试如下所示:
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中没有令牌,您可以在此处找到另一种方法来重定向您的用户
发布于 2018-06-24 23:26:02
只需使用:return <Redirect to="/login" />。这应该可以了。
https://stackoverflow.com/questions/48321489
复制相似问题