添加一个私有路由,当用户未登录时,点击导航的首页历史记录时,自动重定向到登录页面

    1. const PrivateRoute = ({ children }) => {
    2. const { UserStore } = useStore()
    3. const { currentUser } = UserStore
    4. return currentUser ? children : <Navigate to="/login" />
    5. }
    6. function App() {
    7. return (
    8. <>
    9. <Header />
    10. <main>
    11. <Suspense fallback={<Loading />}>
    12. <Routes>
    13. <Route
    14. path="/"
    15. element={
    16. <PrivateRoute>
    17. <Home />
    18. </PrivateRoute>
    19. }
    20. />
    21. <Route path="/about" element={<About />} />
    22. <Route
    23. path="/history"
    24. element={
    25. <PrivateRoute>
    26. <History />
    27. </PrivateRoute>
    28. }
    29. />
    30. <Route path="/login" element={<Login />} />
    31. <Route path="/register" element={<Register />} />
    32. </Routes>
    33. </Suspense>
    34. </main>
    35. <Footer />
    36. </>
    37. )
    38. }