AppRoutes:
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
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;
我正在try 使用REACT-RUTER-V6构建身份验证,并使用zustand进行状态管理,并使用JWT令牌验证用户,其中调用fetchCurrentUser(/auth/currentuser
API)并使用zustand更新useAuth中的用户状态,
和受保护的路由/home
与RequiredAuth,但即使用户验证和状态更新成功,它也是可访问的,或者可以说使用zustand更新的状态在RequidAuth函数中更新.
总是重定向/
我做错了什么?
请帮帮忙,我是相对较新的react ,这将是非常感激.提前谢谢!