正常的行为是在将当前组件重定向到其他路线之前已对其进行渲染?
我的路线列表用Switch
包裹:
const Routes = () => {
return (
<Switch>
<PrivateRoute exact path="/" component={About} />
<LoginRoute path="/login" component={LoginPage} />
<Route component={NotFound} />
</Switch>
);
};
然后,自定义路由组件LoginRoute
会在用户未通过身份验证时重定向到/login
,而PrivateRoute
在用户通过身份验证时会呈现该组件,否则会重定向到/login
LoginRoute:
const LoginRoute = ({ component: Component, ...props }: LoginProps) => {
const auth = useContext(AuthContext);
return (
<Route
{...props}
render={props =>
auth.isAuthenticated ? (
<Redirect
to={{
pathname: "/",
state: {
from: props.location
}
}}
/>
) : (
<Component {...props} />
)
}
/>
);
};
私人路线:
const PrivateRoute = ({
exact,
path,
location,
component: Component,
...props
}: PrivateRouteProps) => {
const auth = useContext(AuthContext);
return (
<Route
exact={exact || false}
path={path}
render={({ location }) =>
auth.isAuthenticated ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: {
from: location
}
}}
/>
)
}
/>
);
};
然后将Router
包装在AuthProvider中。
AuthProvider:
const AuthContextProvider: React.FC<RouteProps> = ({ children }) => {
//states
useEffect(() => {
GetCurrentUser();
}, [state.isAuthenticated]);
const GetCurrentUser = async () => {
await API.get("/user/current")
.then(response => {
setState({
...state,
authenticatedUser: response.data,
isAuthenticated: true,
isRetrieving: false
});
})
.catch(_error => {
setState({
...state,
authenticatedUser: null,
isAuthenticated: false
});
});
};
const SignIn = async (user: UserCredential) => {
await API.post("/user/authenticate", {
...user
})
.then(response => {
setState({
...state,
authenticatedUser: response.data,
isAuthenticated: true,
isRetrieving: false
});
localStorage.setItem(USER_TOKEN, response.data.token);
})
.catch(_error => {
setState({
...state,
authenticatedUser: null,
isAuthenticated: false
});
});
};
const SignOut = () => {
localStorage.removeItem("TOKEN");
};
return (
<AuthProvider
value={{
...state,
signIn: SignIn,
signOut: SignOut,
getCurrentUser: GetCurrentUser
}}
>
{children}
</AuthProvider>
);
};
要花很多时间才能解决这个问题。希望有人可以提供帮助。 当前使用的是React Router v5.1.2