可以通过以下步骤实现:
npm install react-router-dom
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
<Route
{...rest}
render={(props) =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to="/login" />
)
}
/>
);
const App = () => {
const isAuthenticated = // 根据实际情况判断用户是否已成功验证
return (
<Router>
<Switch>
<Route exact path="/login" component={Login} />
<PrivateRoute
isAuthenticated={isAuthenticated}
exact
path="/dashboard"
component={Dashboard}
/>
<PrivateRoute
isAuthenticated={isAuthenticated}
exact
path="/profile"
component={Profile}
/>
<Route path="*" component={NotFound} />
</Switch>
</Router>
);
};
在上述代码中,/login
是登录页面的路径,/dashboard
和/profile
是需要验证的页面路径。Login
、Dashboard
、Profile
和NotFound
是相应页面的组件。
这样,当用户成功验证后,会被重定向到他们所请求的页面,否则会被重定向到登录页面。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云