react-router 的使用

单页面富应用(SPA)

单页面富应用:single-page application,简称SPA;

单页面富应用是指整个Web应用有一个页面,当 url 发生改变时,并不会从服务器请求新的静态资源,而是通过JavaScript监听 url 的改变,并且根据 url 的不同去渲染新的页面(组件)

前端路由

通过监听URL的改变,并且根据 url 的不同去渲染新的页面(组件),复杂这个工作的就是前端路由。

监听 url 的改变有两种方法吗,一种是 url的 hash,另一种是 html5 的 history

url 的 hash

url 的 hash 也就锚点(#),它本质上改变的是 href 属性。另外可以通过直接赋值location.hash 来改变 href

在这里插入图片描述

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    a {
    
      display: inline-block;
      padding: 10px 20px;
      color: #000000;
      text-decoration: none;
      border: 1px solid #eeeeee;
    }
  </style>
</head>
<body>
  <a href="#/home">home</a><a href="#/about">about</a>
  <div id="router-view"></div>
  <script>
    const routerView = document.getElementById('router-view');
    window.addEventListener('hashchange', () => {
    
      switch(location.hash) {
    
        case "#/home":
          routerView.innerHTML = 'home';
          break;
        case "#/about":
          routerView.innerHTML = 'about';
          break;
        default:
          routerView.innerHTML = '404';
      }
    })
  </script>
</body>

html5 的 history

history接口是HTML5新增的, 它有l六种模式改变URL而不刷新页面:

  • replaceState:替换原来的路径;
  • pushState:使用新的路径;
  • popState:路径的回退;
  • go:向前或向后改变路径;
  • forword:向前改变路径;
  • back:向后改变路径;
    在这里插入图片描述
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    a {
    
      display: inline-block;
      padding: 10px 20px;
      color: #000000;
      text-decoration: none;
      border: 1px solid #eeeeee;
    }
  </style>
</head>
<body>
  <a href="/home">home</a>
  <a href="/about">about</a>
  <div id="router-view"></div>
  <script>
    const routerView = document.getElementById('router-view');
    const aList = document.getElementsByTagName('a');
    for (let item of aList) {
    
      item.addEventListener("click", (e) => {
    
        e.preventDefault();
        const href = item.getAttribute("href");
        console.log
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值