react路由配置重定向的两种方式

1,965 阅读1分钟

分析

  • Route 的 render 属性:用来内联渲染任意内容

安装包

  1. 安装路由包:npm i react-router-dom@5.3.0
  2. 安装路由类型声明文件 npm i @types/react-router-dom -D

引入

import { BrowserRouter as Router, Route, Switch, Link, Redirect } from 'react-router-dom'

核心代码

App.tsx 中:


​1. 在 render 中,渲染 Redirect 实现路由重定向可以不用引入Switch
<Route exact path="/" render={() => <Redirect to="/home" />} />
2.使用Redirect标签重定向
<div className="App">
      <Router>
          <Link to='/login'>login</Link>
          <Link to='/layout'>layout</Link>
          <Switch>
          //使用Redirect标签重定向
          <Redirect exact from='/' to='/layout' />
          
          <Route path='/login' component={Login} />
          <Route path='/layout' component={Layout} />
          </Switch>
      </Router>
    </div>