react-router-dom v4 使用指南

59 阅读1分钟

多级路由 (嵌套路由)

代码结构

769d0f662e14fa01924cc22383510e2.jpg

页面效果:路径 http://localhost:3000/dash

image.png 用到的路由组件

  1. <BrowserRouter>
  2. <Switch>
  3. <Route path='' component={}>
  4. <Redirect to=''>

Route 组件相当于一个占位,在路由匹配上的时候,用组件写路由组件的那一块区域就会被 component 里面的组件所替代,由此来实现一个嵌套的路由结构

路由传参

this.props 的结构:this.props 中接收我们传递的参数

image.png 接下来了解一下怎么传

params

  1. 传递方式:在配置路由时用占位的符号,在地址中传递,
  2. 路由代码:<Route path="/dash/:id/:name" component={Dashboard} />
    • 上面的路由规则不能匹配到 http://localhost:3000/dash
  3. 接收效果:http://localhost:3000/dash/1/2?name=tom&age=18

image.png

search

  1. 传递方式:在地址后拼接类似于 ?name=tom&age=18 的形式
  2. 路由代码:注册路由(无需声明,正常注册即可)
  3. 接收效果:

image.png 因为收到的是一个带有格式的字符串,所有需要处理一下: querystring是react自带的

import qs from 'querystring'
const { search } = this.props.location
const res = qs.parse(search.substr(1))

state

  1. 传递方式:使用 Link 组件 <Link to={{ pathname: '/dash', state: { category: 'flower', color: 'red' } }}>测试state传递</Link>
  2. 路由代码:注册路由(无需声明,正常注册即可)
  3. 接收效果:

image.png

函数式路由

使用 this.props.history 携带的方法 函数路由参考

this.props 上没有路由相关方法,无法实现编程式导航?

  1. 原因:普通组件没有在 <Route/> 上注册上就不会有路由相关方法
  2. 解决办法:使用 withRouter(组件) 使一般组件拥有 路由组件的方法