🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 路由重定向 路由重定向目的还是为了进入首页后默认进入一个有信息的页面,或者当用户未登录进行路由重定向等等。 ``` <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组件节省性能。