# 路由重定向
路由重定向目的還是為了進入首頁后默認進入一個有信息的頁面,或者當用戶未登錄進行路由重定向等等。
```
<Redirect to={'/home'} />
```
```
import React, {Component, Fragment} from 'react'
import {Link, Route,Redirect} from "react-router-dom";
import Home from "./pages/Home";
import NewsCenter from "./pages/NewsCenter";
import News from "./pages/News";
import About from "./pages/About";
import style from './app.css'
export default class App extends Component {
constructor(props) {
super(props)
this.state = {}
console.log(this);
}
render() {
let {pathname} = this.props.location
return (
<Fragment>
{/*導航 Link vue的用法很相似*/}
<Link to={"/home"} className={pathname == '/home' ? style.active: ''}>首頁</Link>
<Link to={"/news/1"} className={pathname == '/news/1' ? style.active : ''}>新聞</Link>
<Link to={"/news"} className={pathname == '/news' ? style.active : ''}>新聞中心</Link>
<Link to={"/about"} className={pathname == '/about' ? style.active : ''}>關于</Link>
{/*路由指向到哪個頁面 指的是組件*/}
<Route path={'/home'} component={Home}/>
<Route path={'/news'} component={NewsCenter} exact/>
<Route path={'/news/:id'} component={News} exact/>
<Route path={'/about'} component={About}/>
<Redirect to={'/home'} />
</Fragment>
)
}
}
```
上面這樣寫完之后會報錯,因為它會認為每個頁面都需要重新跳轉到’home'組件中。原因是因為React路由的原理是從上向下逐一匹配,到了最后一項就會重定向。這樣就會導致死循環。
如何解決?
# Switch路由組件
```
<Switch>
<Route path={'/home'} component={Home}/>
<Route path={'/news'} component={NewsCenter} exact/>
<Route path={'/news/:id'} component={News} exact/>
<Route path={'/about'} component={About}/>
<Redirect to={'/home'} />
</Switch>
```
switch其實就和JS中的switch 只會匹配一個。就不再報錯了。可以在理解上認為沒有Switch組件就相當于if else 有switch 就是JS的switch
# 總結
以后書寫路由必須書寫Switch組件節省性能。
- webpack復習
- React基礎
- 前端三大主流框架對比
- React中幾個核心的概念
- React基礎語法
- React JSX語法
- React組件
- 普通組件
- 組件通信-父向子傳遞
- 組件拆成單個文件
- 面向對象復習
- Class組件基礎
- Class組件的私有狀態(私有數據)
- 案例:實現評論列表組件
- 組件樣式管理
- 組件樣式分離-樣式表
- CSS模塊化
- 生命周期
- React組件生命周期
- Counter組件來學習組件生命周期
- 生命周期總結
- 生命周期案例
- React評論列表
- React雙向數據綁定
- React版todolist
- 其它提高(了解)
- 組件默認值和數據類型驗證
- 綁定this并傳參的三種方式
- 祖孫級和非父子組件傳遞數據(了解)
- React路由
- 路由基礎
- 動態路由
- 路由嚴格模式
- 路由導航定位
- 路由重定向
- 路由懶加載
- WolfMovie項目
- 項目初始化
- AntDesign使用
- 其它相關了解