应用程序路线:
function AppRoutes(): JSX.Element {
return (
<Routes>
<Route path="/" element={<Auth />} />
<Route element={<RequiredAuth />}>
<Route path="/home" element={<Home />} />
</Route>
</Routes>
);
}
私人路线检查
import { Navigate, Outlet } from "react-router-dom";
import useAuth from "./hooks/useAuth";
const RequiredAuth = () => {
const { user } = useAuth();
console.log("USERAUTH", user);
return user ? <Outlet /> : <Navigate to="/" replace />;
};
export default RequiredAuth;
useAuth Hook 与 zustand 商店
import { create } from "zustand";
import axios, { AxiosResponse } from "axios";
import apiSecure, { api } from "../libs/axios";
type user = {
id: string;
};
interface useAuthStore {
user: user | null;
signIn: (username: string, password: string) => Promise<void>;
fetchCurrentUser: () => Promise<void>;
}
interface AuthResponse {
code: number;
error: boolean;
message: string;
data: {
email: string;
id: string;
name: string;
token: string;
username: string;
};
errors?: [];
}
const useAuth = create<useAuthStore>((set) => ({
user: null,
signIn: async (username: string, password: string): Promise<void> => {
// login process
},
fetchCurrentUser: async (): Promise<void> => {
try {
const response: AxiosResponse<AuthResponse> = await apiSecure.get(
`/auth/currentuser`
);
const userData = response.data.data;
set({ user: { id: userData.id } });
console.log("SETUP", { id: userData.id });
} catch (error: unknown) {
// Handle authentication errors
}
},
}));
export default useAuth;
function App(): JSX.Element {
const { fetchCurrentUser, user } = useAuth();
console.log(user);
useEffect(() => {
async function auth() {
await fetchCurrentUser();
}
auth();
}, [fetchCurrentUser]);
// useEffect(() => {}, [fetchCurrentUser])
return (
<>
<AppRoutes />
</>
);
}
export default App;
我正在尝试使用react-router-v6构建身份验证,并使用zustand进行状态管理,并使用jwt令牌验证用户,调用fetchcurrentuser(
/auth/currentuser
api)并使用zustand更新useAuth中的用户状态,
和受RequiredAuth保护的路由/home
,但即使用户验证并成功更新状态,也可以访问它,或者可以说用zustand更新的状态在requiredAuth函数中更新。
它总是重定向
/
我做错了什么?
请帮忙,我对反应还比较陌生,非常感谢。预先感谢!
用
Routes
括住您的 BrowserRouter
。
<BrowserRouter>
<Routes>
<Route path="/" element={<Auth />} />
<Route element={<RequiredAuth />}>
<Route path="/home" element={<Home />} />
</Route>
</Routes>
</BrowserRouter>
这可能是错误的原因。