gpt4 book ai didi

reactjs - React Router 在重定向中包装多个路由

转载 作者:行者123 更新时间:2023-12-02 03:20:18 25 4
gpt4 key购买 nike

给定一个身份验证 token 和一个函数 checkToken 我将如何使用 react 路由器从多个路由重新路由以防止像下面这样的重复?

<Route exact path="/" render={() => {
return checkToken() ? (<Dashboard />) : (<Redirect to="/login" />)
}} />
<Route exact path="/about" render={() => {
return checkToken() ? (<About />) : (<Redirect to="/login" />)
}} />

如果我有几十条路线要重复此操作,那就会很麻烦。

肯定有更好的方法!

最佳答案

我喜欢这样处理这个问题:

  1. src中创建一个routers文件夹
  2. 在路由器文件夹内创建 3 个文件 AppRouter.jsPrivateRoute.jsPublicRoute.js

这是您的PublicRoute.js:

import React from 'react';
import { connect } from 'react-redux';
import { Route, Redirect } from 'react-router-dom';

export const PublicRoute = ({ isAuthenticated, component: Component, ...rest }) => (
<Route {...rest} component={(props) => (
isAuthenticated ? <Redirect to="/dashboard" /> : <Component {...props} />
)} />
);

const mapStateToProps = state => ({
isAuthenticated: // however you need to keep track of that...
});

export default connect(mapStateToProps)(PublicRoute);

这是您的PrivateRoute.js:

import React from 'react';
import { connect } from 'react-redux';
import { Route, Redirect } from 'react-router-dom';

export const PrivateRoute = ({ isAuthenticated, component: Component, ...rest }) => (
<Route {...rest} component={(props) => (
isAuthenticated ? <Component {...props} /> : <Redirect to="/" />
)} />
);

const mapStateToProps = state => ({
isAuthenticated: // however you need to keep track of that...
});

export default connect(mapStateToProps)(PrivateRoute);

最后这是您的 AppRouter.js:

import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

import Dashboard from '../components/Dashboard';
import NotFound from '../components/NotFound';
import Login from '../components/Login';
import PrivateRoute from './PrivateRoute';
import PublicRoute from './PublicRoute';



const AppRouter = () => (
<BrowserRouter>
<Switch>
{/* use PublicRoute for public routes */}
<PublicRoute exact path="/" component={Login} />
{/* use PrivateRoute for private routes */}
<PrivateRoute path="/dashboard" component={Dashboard} />
<Route component={NotFound} />
</Switch>
</BrowserRouter>
);

export default AppRouter;

有关 HOC(高阶组件)的更多信息,请查找文档:https://reactjs.org/docs/higher-order-components.html

关于reactjs - React Router 在重定向中包装多个路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55032376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com