我正在使用 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")
);
最佳答案
你可以尝试这样的事情:
import createHistory from 'history/createBrowserHistory';
const history = createHistory({
window.location.pathname,
});
// ...
if(error.response.status === 401) {
// ...
history.push('/login');
}
如果本地存储中没有 token ,您可以在这里找到另一种方法来重定向用户:https://github.com/strapi/strapi-examples/blob/master/login-react/react-login-front-end-app/app/containers/WithAuth/index.js
关于reactjs - 从函数重定向 React Router,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48321489/