使用私有路由,使购物车页面只有登录了才能访问
参考
react-router v6 写法
import styles from './App.module.css'
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import {
HomePage,
SignInPage,
RegisterPage,
DetailPage,
ShoppingCart,
} from './pages'
import { useSelector } from './redux/hooks'
const PrivateRoute = ({ isAuthenticated, children }) => {
return isAuthenticated ? children : <Navigate to="/signIn" />
}
function App() {
const jwt = useSelector((s) => s.user.token)
return (
<div className={styles.App}>
<BrowserRouter>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/signIn" element={<SignInPage />} />
<Route path="/register" element={<RegisterPage />} />
<Route path="/detail/:touristRouteId" element={<DetailPage />} />
<Route
path="/shoppingCart"
element={
<PrivateRoute isAuthenticated={jwt !== null}>
<ShoppingCart />
</PrivateRoute>
}
/>
<Route path="*" element={<div>404 not found</div>} />
</Routes>
</BrowserRouter>
</div>
)
}
export default App
react-router v5写法
import React from 'react';
import styles from "./App.module.css";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import {
HomePage,
SignInPage,
RegisterPage,
DetailPage,
SearchPage,
ShoppingCartPage,
} from "./pages";
import { Redirect } from "react-router-dom";
import { useSelector } from "./redux/hooks";
const PrivateRoute = ({ component, isAuthenticated, ...rest }) => {
const routeComponent = (props) => {
return isAuthenticated ? (
React.createElement(component, props)
) : (
<Redirect to={{ pathname: "/signIn" }} />
);
}
return <Route render={routeComponent} {...rest} />;
}
function App() {
const jwt = useSelector((s) => s.user.token);
return (
<div className={styles.App}>
<BrowserRouter>
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/signIn" component={SignInPage} />
<Route path="/register" component={RegisterPage} />
<Route path="/detail/:touristRouteId" component={DetailPage} />
<Route path="/search/:keywords?" component={SearchPage} />
<PrivateRoute
isAuthenticated={jwt !== null}
path="/shoppingCart"
component={ShoppingCartPage}
/>
<Route render={() => <h1>404 not found 页面去火星了 !</h1>} />
</Switch>
</BrowserRouter>
</div>
);
}
export default App;