这里展示了React-Router v6中最基本的身份验证实现。PrivateRoutes
中的loggedIn
标志在更新上下文后更新为true时不会改变,因此在导航到它们时无法访问私有路由。为什么会这样?
import './App.css';
import {
BrowserRouter,
Navigate,
Outlet,
Route,
Routes,
useNavigate
} from 'react-router-dom';
import React, { useState } from 'react';
function App() {
return (
<div>
<AuthProvider>
<BrowserRouter>
<Routes>
<Route path="/" element={<HomePage />} />
<Route element={<PrivateRoutes />}>
<Route path="/secret" element={<SecretPage />} />
{/** ... Other protected pages ...*/}
</Route>
</Routes>
</BrowserRouter>
</AuthProvider>
</div>
);
}
function PrivateRoutes() {
const { loggedIn } = useAuth();
return loggedIn ? <Outlet />: <Navigate to="/" />
}
function HomePage() {
const navigate = useNavigate();
return <>
<h1>Home page</h1>
<button onClick={() => navigate('/secret')}>
Go to secret page
</button>
</>
}
function SecretPage() {
return <>
<h1>Secret Page</h1>
</>
}
const AuthContext = React.createContext()
const AuthProvider = ({ children }) => {
const { loggedIn, signIn } = useAuth()
return
<AuthContext.Provider value={loggedIn}>
{/**
* Button to trigger sign in and showing the
* current status.
*/}
<button onClick={signIn}>LogIn</button>
<h2>Logged In: {loggedIn.toString()}</h2>
<p>-----------------------</p>
{children}
</AuthContext.Provider>
}
const useAuth = () => {
const [loggedIn, setLoggedIn] = useState(false)
const signIn = () => {
{/** sign in logic ....*/}
setLoggedIn(true);
};
return { loggedIn, signIn };
}
export default App;
2条答案
按热度按时间jaxagkaj1#
useAuth
是一个React钩子,React钩子不共享内部状态。useAuth
的每个示例都有自己独立的loggedIn
状态。重构
AuthProvider
以保持loggedIn
状态,并更新useAuth
钩子以使用提供的上下文值。这就是所有useAuth
示例都获得相同值的方式。sh7euo9m2#
试试这个