import React from "react";
import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
// 需要进行路由守卫的组件
const PrivateComponent = () => <h1>Private Component</h1>;
// 路由守卫
const AuthGuard = ({ when, navigate, path, ...rest }) => {
if (when) {
return <Route {...rest} />;
} else {
navigate("/login");
return null;
}
};
// App组件
const App = () => (
<Router>
<div>
<h1>React Router Demo</h1>
<Routes>
<AuthGuard
path="/private"
element={<PrivateComponent />}
when={isLoggedIn()} // 自定义判断登录状态的函数
/>
</Routes>
</div>
</Router>
);
// 自定义函数:判断用户是否已登录
const isLoggedIn = () => {
// 判断用户是否已经登录,返回 true 或 false
return true;
}
export default App;