使用私有路由,使购物车页面只有登录了才能访问
    参考
    react-router v6 写法

    1. import styles from './App.module.css'
    2. import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
    3. import {
    4. HomePage,
    5. SignInPage,
    6. RegisterPage,
    7. DetailPage,
    8. ShoppingCart,
    9. } from './pages'
    10. import { useSelector } from './redux/hooks'
    11. const PrivateRoute = ({ isAuthenticated, children }) => {
    12. return isAuthenticated ? children : <Navigate to="/signIn" />
    13. }
    14. function App() {
    15. const jwt = useSelector((s) => s.user.token)
    16. return (
    17. <div className={styles.App}>
    18. <BrowserRouter>
    19. <Routes>
    20. <Route path="/" element={<HomePage />} />
    21. <Route path="/signIn" element={<SignInPage />} />
    22. <Route path="/register" element={<RegisterPage />} />
    23. <Route path="/detail/:touristRouteId" element={<DetailPage />} />
    24. <Route
    25. path="/shoppingCart"
    26. element={
    27. <PrivateRoute isAuthenticated={jwt !== null}>
    28. <ShoppingCart />
    29. </PrivateRoute>
    30. }
    31. />
    32. <Route path="*" element={<div>404 not found</div>} />
    33. </Routes>
    34. </BrowserRouter>
    35. </div>
    36. )
    37. }
    38. export default App

    react-router v5写法

    1. import React from 'react';
    2. import styles from "./App.module.css";
    3. import { BrowserRouter, Route, Switch } from "react-router-dom";
    4. import {
    5. HomePage,
    6. SignInPage,
    7. RegisterPage,
    8. DetailPage,
    9. SearchPage,
    10. ShoppingCartPage,
    11. } from "./pages";
    12. import { Redirect } from "react-router-dom";
    13. import { useSelector } from "./redux/hooks";
    14. const PrivateRoute = ({ component, isAuthenticated, ...rest }) => {
    15. const routeComponent = (props) => {
    16. return isAuthenticated ? (
    17. React.createElement(component, props)
    18. ) : (
    19. <Redirect to={{ pathname: "/signIn" }} />
    20. );
    21. }
    22. return <Route render={routeComponent} {...rest} />;
    23. }
    24. function App() {
    25. const jwt = useSelector((s) => s.user.token);
    26. return (
    27. <div className={styles.App}>
    28. <BrowserRouter>
    29. <Switch>
    30. <Route exact path="/" component={HomePage} />
    31. <Route path="/signIn" component={SignInPage} />
    32. <Route path="/register" component={RegisterPage} />
    33. <Route path="/detail/:touristRouteId" component={DetailPage} />
    34. <Route path="/search/:keywords?" component={SearchPage} />
    35. <PrivateRoute
    36. isAuthenticated={jwt !== null}
    37. path="/shoppingCart"
    38. component={ShoppingCartPage}
    39. />
    40. <Route render={() => <h1>404 not found 页面去火星了 !</h1>} />
    41. </Switch>
    42. </BrowserRouter>
    43. </div>
    44. );
    45. }
    46. export default App;