我创建了一个 Login
组件,它在成功验证后将我再次重定向回 Login
。相反,它应该重定向到位于 "/"
的 PrivateRoute。我的 handleSubmit
组件中的 Login
函数如下所示:
function handleSubmit(e) {
setLoading(true);
e.preventDefault();
authenticationService.login(email, password)
.then((res) => {
console.log(res.data);
setLoading(false);
history.push("/");
console.log(authenticationService.isAuthenticated);
})
.catch((error) => {
console.log(error);
setLoading(false);
setError(error.message || error);
});
}
我可以看到 console.log(authenticationService.isAuthenticated)
是 false
,所以当 Login
运行时我被重定向到 history.push("/")
的原因可以在 PrivateRoute
- 我还没有通过身份验证,所以它会发送回 Login
:
import { Redirect, Route } from "react-router";
import { authenticationService } from "./services";
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={(props) => {
if (authenticationService.isAuthenticated) {
return <Component {...props} />;
}
return <Redirect to="/login" />;
}}
/>
);
export default PrivateRoute;
我的问题是:处理这个问题的推荐方法是什么。由于这肯定是一个非常频繁的用例,我想有一个标准程序可以使其正常工作。
如果有帮助,我的 authenticationService.login
如下所示:
// authentication.service.js
import axios from "axios";
import { api } from "../api";
const authAxios = axios.create();
authAxios.interceptors.request.use((config) => {
const newConfig = config;
const token = localStorage.getItem("token");
console.log(token);
newConfig.headers = {
Authorization: `Token ${token}`,
};
return newConfig;
});
function isAuthenticated() {
const token = localStorage.getItem("token");
return token !== null && token !== undefined;
}
function login(email, password) {
return axios
.post(api.auth.login, {
email,
password,
})
.then((res) => {
localStorage.setItem("token", res.data.key);
return res;
});
}
function logout() {
localStorage.removeItem("token");
}
const authenticationService = {
isAuthenticated: isAuthenticated(),
login,
logout,
};
export { authAxios, authenticationService };