If I refresh the page, I go to the user component and the app goes through my protected route.
我的寄存器中发生了同样的事情,用户被插入但从未被重定向。登录组件:
登录组件:
function handleSubmit(e) {
e.preventDefault();
setSubmitted(true);
if (email && password) {
const data = { email, password };
console.log(data);
const { from } = location.state || { from: { pathname: "/user" } };
dispatch(loginUser(data, from));
}
}
登录服务:
export const loginUser = (data: UserInterface, from: any) => (
dispatch: Dispatch
) => {
axios
.post("http://localhost:3000/api/users/login", data)
.then((res) => {
//Save to localstorage
//Set token to localStorage
const { access_token } = res.data;
localStorage.setItem("JWT_TOKEN", access_token);
//set token to auth header
setAuthToken(access_token);
//decode token to get user data
const decoded = jwt_decode(access_token);
//set current user
dispatch(setCurrentUser(decoded));
history.push(from);
})
.catch((error) => {
throw error;
});
};
受保护的路线:
import React from "react";
import { Route, Redirect, RouteProps } from "react-router-dom";
import { useSelector } from "react-redux";
interface IPrivateRouteProps extends Omit<RouteProps, "component"> {
component: React.ElementType;
roles: string[];
}
const PrivateRoute = ({
component: Component,
roles = [],
...rest
}: IPrivateRouteProps) => {
console.log("aqui");
const auth = useSelector((state: any) => state.auth);
const hasRole = roles.some(role => roles.includes(role));
console.log(hasRole)
return (
<Route
{...rest}
render={(props) =>
auth.isAuthenticated === true && hasRole ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: "/", state: { from: props.location } }} />
)
}
/>
);
};
export default PrivateRoute;
应用
<Router>
<Switch>
{routesConfig.routes.map(({ component, roles, url }) =>
roles.length ? (
<PrivateRoute
exact
path={url}
component={component}
roles={roles}
/>
) : (
<Route exact path={url} component={component} />
)
)}
</Switch>
</Router>
```
Routes
export default {
routes: [
{
component: Login,
url: "/login",
roles: [],
}
如果有人有时间运行代码,那就去吧! https://github.com/FACorreiaa/RecipePlatformClient