React Router以重定向方式包装多条路由

时间:2019-03-06 21:24:44

标签: reactjs react-router router

给出一个身份验证令牌和一个函数checkToken,我将如何使用react路由器从多个路由重新路由以防止重复如下所示?

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

如果我有几十条路线要重复进行,会很麻烦。

肯定有更好的方法!

2 个答案:

答案 0 :(得分:1)

这是我喜欢的处理方式:

  1. routers中创建一个src文件夹
  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

答案 1 :(得分:0)

一种实现方法是将checkToken函数放置在componentDidMount内,这样每次安装该组件时,您始终会检查用户是否通过了身份验证。

之后,您可以执行以下操作:

let routes = (
  <Switch>
    <Route path="/login" component={LoginComponent} />
    <Redirect to="/" />
  </Switch>
);
if (isAuth) {
  routes = (
    <Switch>
      <Route path="/yourRoute" component={YourComponent} />
      <Redirect to="/" />
    </Switch>
  );
}

return (
  <div>
    {routes}
  </div>