react-router-dom

134 阅读2分钟

安装

npm install react-router-dom@5

路由的基本使用

  1. 明确界面中导航区、标签区
  2. 导航区的a标签改为Link组件
<link to='/about'>关于<Link>
  1. 展示区写Route组件进行路径的匹配
<Route path="/about" component={About}></Route>
  1. <App>的最外层包裹一个<BrowserRouter><HashRouter>

路由组件和一般组件

  1. 写法不同
  2. 存放位置不同(规范做法中),一般组件放在components,路由组件放在pages
  3. 接受到props不同 一般组件:写组件标签时传递了什么,就能收到什么 路由组件:
history: {
    go: ƒ go(n)
    goBack: ƒ goBack()
    goForward: ƒ goForward()
    push: ƒ push(path, state)
    replace: ƒ replace(path, state)
}
location: {
    hash""
    pathname"/about"
    search""
}
match: {
    params: {}
    path"/about"
    url"/about"
}

Switch的使用

  1. 通常请款下,path和componet是一一对应的
  2. Switch可以提高路由匹配效率(单一匹配)
<Switch>
    <Route path="/about" component={About}/>
    <Route path="/home" component={Home}/>
    <Route path="/todo" component={Todo}/>
</Switch>

解决多级路径刷新页面样式丢失的问题

  1. public/index.html 中引入样式不写.//(常用)
  2. public/index.html 中引入样式不写./%PUBLIC_URL%(常用)
  3. 使用HashRouter

路由的严格匹配和模糊匹配

  1. 默认请使用的是模糊匹配(输入路径必须包含匹配路径,且顺序一致)
  2. 开启严格模式<Route exact={true} path='about' component={About}/>
  3. 严格匹配不要随意开启,需要再开,有时候开会导致无法继续匹配二级路由

Redirect的使用

  1. 一般卸载路由注册的最下方,当所有的路由都无法匹配是,跳转到Redirect指定的路由
  2. 具体编码
<Switch>
    <Route path="/about" component={About}/>
    <Route path="/home" component={Home}/>
    <Route path="/todo" component={Todo}/>
    <Redirect to="/about"></Redirect>
</Switch>

嵌套路由

  1. 注册资路由时要协商父路由的path值
  2. 路由的匹配时按咋后注册路由的顺序进行的

向路由组件传递数据

  1. paras参数
    • 路由链接(携带参数): <Link to={/home/message/detail/${mes.id}}>{mes.text}</Link>
    • 注册路由(声明参数):<Route path="/home/message/detail/:id" component={MessageDetail}></Route>
    • 接受参数: const {id} = this.props.match.params;
  2. search参数
    • 路由链接(携带参数): <Link to={/home/message/detail?id=${mes.id}}>{mes.text}</Link>
    • 注册路由(无需声明,正常注册即可):<Route path="/home/message/detail" component={MessageDetail}></Route>
    • 接受参数: const {id} = this.props.location.search;
    • 备注:获取到的seach时urlencode编码字符串,需要借助querystring解析
  3. state参数
    • 路由链接(携带参数): <Link to={{path: '/home/message/detail', state: {id: mes.is}}}>{mes.text}</Link>

    • 注册路由(无需声明,正常注册即可):<Route path="/home/message/detail" component={MessageDetail}></Route>

    • 接受参数: const {id} = this.props.location.state;

    • 备注:刷新也可以保留参数,但是清除浏览器缓存后,参数不可保留

BrowserRouter和HashRouter的区别

  1. 底层原理不一样
    • BrowserRouter使用的是H5的histroy API,不兼容IE9及以下版本
    • HashRouter使用的是URL的哈希值
  2. path表现不一样
    • BrowserRouter的路径中没有#,例如:localtion:3000/home
    • HashRouter的路径包含#,例如:localtion:300/#/home
  3. 刷新后对路由state参数的影响
    • BrowserRouter没有任何影响,因为state保存在history对象中
    • HashRouter刷新后回导致路由state参数的丢失