react系列学习(五)——react-router-dom5.X的使用及相关问题详解

 1、例子界面如下图:


2、代码:

2.1、主页面:

import { HashRouter, Route, Switch, Link, Redirect } from 'react-router-dom';
<HashRouter>
   <div className="App">
       hello react
       <br />
       <Link to='/redux'>
         <span>redux示例</span>
       </Link>
       <Link to='/reduxRedux'>
          <span>react-redux示例</span>
       </Link>
       <Link to='/topics'>
          <span>router嵌套示例</span>
       </Link>
       <Switch> 
         <Route path='/redux' exact >
            <Account />
         </Route>
         <Route path='/reduxRedux' exact >
            <AccoutRedux />
         </Route>
         <Route path='/topics'>
            <Topics />
         </Route>
         //重定向
         <Redirect to="/redux" from='/' exact /> 
      </Switch>
   </div>
</HashRouter>

2.2、嵌套路由

Topics.js组件

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useRouteMatch,
  useParams
} from "react-router-dom";
import Topic from '../Topic';

function Topics() {
  let match = useRouteMatch();
  console.log('match =>',match);

  return (
    <div>
      <h2>Topics</h2>

      <ul>
        <li>
          <Link to={`${match.url}/components`}>Components</Link>
        </li>
        <li>
          <Link to={`${match.url}/props-v-state`}>
            Props v. State
          </Link>
        </li>
      </ul>

      {/* The Topics page has its own <Switch> with more routes
          that build on the /topics URL path. You can think of the
          2nd <Route> here as an "index" page for all topics, or
          the page that is shown when no topic is selected */}
      <Switch>
        <Route path={`${match.path}/:topicId`}>
          <Topic />
        </Route>
        <Route path={match.path}>
          <h3>Please select a topic.</h3>
        </Route>
      </Switch>
    </div>
  );
}
export default Topics;

2.3、Topic.js组件

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useRouteMatch,
  useParams
} from "react-router-dom";

function Topic() {
  let { topicId } = useParams();
  return <h3>Requested topic ID: {topicId}</h3>;
}

export default Topic;

3、exact:bool

完全(严格)匹配。嵌套路由时不要用,比如上述例子  <Route path='/topics'><Topics /></Route>,如果用了exact,则匹配不到‘/topicc/:topicId’。因为先从一级路由开始匹配。

4、NavLink

Link的升级版,可设置链接高亮。默认加“active”类名,如果要改变类名,可加“activeClassName="xxx"”。

5、封装NavLink

import React, { Component } from 'react'
import {NavLink} from 'react-router-dom'

export default class MyNavLink extends Component {
	render() {
		// console.log(this.props);
		return (
			<NavLink activeClassName="atguigu" className="list-group-item" {...this.props}/>
		)
	}
}


//使用方法
<MyNavLink to="/home">Home</MyNavLink>

说明:

1)标签体内容,可以通过props接收,key值为children,即props.children

2)标签体内容也是特殊的标签属性

<NavLink activeClassName="atguigu" className="list-group-item">{this.props.children}</NavLink>
//等同于
<NavLink activeClassName="atguigu" className="list-group-item" children={this.props.children}/>

6、Switch的作用

1)通常情况下,path和component是一一对应关系

2)Switch可以提高路由匹配效率(单一匹配)

通俗的讲,可以理解为:Switch用于匹配到路由后,不会再向下继续匹配

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

        1).public/index.html 中 引入样式时不写 ./ 写 / (常用)

        2).public/index.html 中 引入样式时不写 ./ 写 %PUBLIC_URL% (常用)

        3).使用HashRouter

8、向路由组件传递参数

        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.search

              备注:获取到的search是urlencoded编码字符串(key=value&key=value),需要借助querystring解析(react脚手架已经下载好了)

        3).state参数

              路由链接(携带参数):<Link to={{pathname:'/demo/test',state:{name:'tom',age:18}}}>详情</Link>

              注册路由(无需声明,正常注册即可):<Route path="/demo/test" component={Test}/>

              接收参数:this.props.location.state

              备注:刷新也可以保留住参数

9、BrowserRouter与HashRouter的区别

      1.底层原理不一样:

            BrowserRouter使用的是H5的history API,不兼容IE9及以下版本。

            HashRouter使用的是URL的哈希值。

      2.path表现形式不一样

            BrowserRouter的路径中没有#,例如:localhost:3000/demo/test

            HashRouter的路径包含#,例如:localhost:3000/#/demo/test

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

            (1).BrowserRouter没有任何影响,因为state保存在history对象中。

            (2).HashRouter刷新后会导致路由state参数的丢失!!!

      4.备注:HashRouter可以用于解决一些路径错误相关的问题。

10、默认push,如果想用replace,可在Link上加"replace"属性即可。

11、编程式路由导航

          借助this.prosp.history对象上的API对操作路由跳转、前进、后退

              -this.prosp.history.push()

              -this.prosp.history.replace()

              -this.prosp.history.goBack()

              -this.prosp.history.goForward()

              -this.prosp.history.go()

12、路由组件与一般组件(vue不区分)

      1.写法不同:

            一般组件:<Demo/>

            路由组件:<Route path="/demo" component={Demo}/>

      2.存放位置不同:

            一般组件:components

            路由组件:pages

      3.接收到的props不同:

            一般组件:写组件标签时传递了什么,就能收到什么

            路由组件:接收到三个固定的属性

                      history:

                            go: ƒ go(n)

                            goBack: ƒ goBack()

                            goForward: ƒ goForward()

                            push: ƒ push(path, state)

                            replace: ƒ replace(path, state)

                      location:

                            pathname: "/about"

                            search: ""

                            state: undefined

                      match:

                            params: {}

                            path: "/about"

                            url: "/about"

13、widthRouter

widthRouter可以加工一般组件,让一般组件具备路由组件所特有的API

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值