什么是路由
- 路由是根据不同的 url 地址展示不同的内容或者页面。
- 在 react 中,react-router-dom 包,可以友好的帮我们解决 react components 到 url 之间的同步映射关系。
使用路由
-
安装路由
$ npm install react-router-dom -S
-
引入路由
import React, { Component } from 'react' // 引入路由文件 import { HashRouter, // 哈希模式 BrowserRouter, // history 模式 Route, Link, Redirect, // 重定向 Switch } from 'react-router-dom'
-
定义路由以及路由重定向
- react 中路由,默认会进行模糊匹配,且不会自动停止
- 加上 Switch 进行模糊匹配,匹配到第一个就停止匹配,也可以加上 exact,实现精准匹配
export default class Router extends Component { render() { return ( <HashRouter> <Switch> <Route path="/home" component={Home}/> <Router path="/login" component={Login}/> <Redirect from="/" to="/home" exact/> <Route path="*" component={NotFound}/> </Switch> </HashRouter> ) } }
-
嵌套路由
- 在对应的子组件中,引入路由,配置路由即可
export default class Home extends Component { render() { return ( <div>子组件中配置子路由</div> <Switch> <Route path="/list" component={List}/> <Redirect from="/" to="/list"/> </Switch> ) } }
-
路由拦截
- 使用三目运算对路由进行拦截
export default class Router extends Component { render() { return ( <HashRouter> <Switch> <Route path="/login" compoent={Login}/> <Route path="/" render={()=>{ localStorage.getItem('isLogin') ? <DashBoard /> : <Redirect to="/login"/> }}/> </Switch> </HashRouter> ) } }
-
声明式导航
- 利用 NavLink 标签 to 属性实现路由的跳转
- activeClassName 可以给激活状态元素加上对应类名
export default class NavBar extends Component { render() { return ( <ul> <li> <NavLink to="/home" activeClassName="active">主页</NavLink> </li> <li> <NavLink to="/list" activeClassName="active">列表页</NavLink> </li> <li> <NavLink to="/center" activeClassName="active">个人中心</NavLink> </li> </ul> ) } }
-
编程式导航
- this.props.history.push()
clickHandle = (id) => { this.props.history.push(`/detail/${id}`) } // detail 页面接收动态参数: this.props.match.params.id
-
路由传参
// 方式一: 利用 this.props.location.query 接收 this.props.history.push({ pathname: '/user', query: { a: 1, b: 2 } }) // 方式二:利用 this.props.location.state 接收 this.props.history.push({ pathname: '/user', state: { a: 1, b: 2 } })
-
withRouter 高阶组件
- 普通组件如果没有使用路由的话, this.props 上是没有 history、location、match 等属性的
- 如果我们在普通组件中需要用到这些属性,则可以借用 withRouter 来实现
import React, { Component } from 'react' // 引入高阶组件 import { withRouter } from 'react-router' class TopBar extends Component { render() { return ( <div> <button onClick={this.exit}>退出登录</button> </div> ) } exit = () => { //清除本地存储 localStorage.removeItem('token') // 跳转到登录页 this.props.history.push('/login') } } // 使用高阶组件,为 TopBar 传递 history、location、match 等属性 export default withRouter(TopBar)