美文网首页
react-router-dom部分笔记

react-router-dom部分笔记

作者: 不退则进_笑 | 来源:发表于2021-04-12 16:30 被阅读0次

1,向路由组建传递参数

(1)params 参数

  • 路由链接(携带参数):
<Link to = 'demo/test/tom/18'>详情</Link>
  • 注册路由(声明接收)
<Route path = 'demo/test/:name/:age' component={Test}/>
  • 接收参数
    this.props.match.params

(2)search 参数

  • 路由链接(携带参数):
<Link to = 'demo/test?name=tom&age=18'>详情</Link>
  • 注册路由(无需声明,正常注册即可)
<Route path = 'demo/test' component={Test}/>
  • 接收参数
    this.props.location.serach

  • 备注:
    获取到的 search 是 urlencoded 编码字符串,需要借助 querystring 解析

(3)state 参数

  • 路由链接(携带参数):
<Link to = {{pathname:'demo/test',state:{name:'tom',age:18}}}>详情</Link>
  • 注册路由(无需声明,正常注册即可)
<Route path = 'demo/test' component={Test}/>
  • 接收参数
    this.props.location.state

  • 备注:
    刷新浏览器也可以保留住参数

2,编程式路由导航

  • 携带 params 参数
this.props.history.push(`/home/message/${info.id}/${info.title}`)
  • 携带 search 参数
 this.props.history.push(`/home/message?id=${info.id}&name=${info.title}`)
  • 携带 state 参数
 方式一:
 this.props.history.push(`/home/message`,{id: info.id, name:info.title})

 方式二:
 this.props.history.push({
      pathname: '/!F1-analysis/!S2-newPlatform/basic',
      state: { item:1 },
      query:{name:'zx'}
    })
  • 借助 this.props.history 对象上的 API 对操作路由跳转、前进、后退
this.props.history.push()
this.props.history.replace()
this.props.history.goBack() // 后退
this.props.history.goForward() //前进
this.props.history.go() 前进或后退几步

3,BrowserRouter 与 HashRouter 的区别

(1)底层原理不一样

  • HashRouter 使用的是 URL 的 hash 值
  • BrowserRouter 使用的是 react 的 H5 的 historyAPI,不兼容 IE9 及一下

(2)path 表现形式不一样

  • HashRouter 的路径有#
  • BrowserRouter 的路径没有#

(3)刷新后对路由 state 参数的影响

  • HashRouter 刷新后会导致路由 state 参数的丢失
  • BrowserRouter 没有任何影响,因为 state 保存在 history 对象中
  • 总结:只要使用 HashRouter 就不要使用 state 参数了

(4)HashRouter 可以用于解决一些路径错误相关的问题

相关文章

网友评论

      本文标题:react-router-dom部分笔记

      本文链接:https://www.haomeiwen.com/subject/qbpxlltx.html