React 学习笔记 12 (路由的实现原理)

路由的实现方式有两种,一种是基于hash实现的hashRouter,一种是基于 history实现的BrowserRouter,下面我们分类简单介绍一下他的底层实现的原理

1.基于hash的hashRouter,监听hanshchange事件获取当前的路径

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #root {
            border: 1px solid red;
            height: 200px;
        }
    </style>
</head>

<body>
    <a href="#/a">跳转到/a</a>
    <a href="#/b">跳转到/b</a>
    <div id="root"></div>
</body>
<script>
    let container = document.getElementById('root');
    window.addEventListener('hashchange', event => {
        console.log(event)
        // container.innerHTML = event.newURL
        container.innerHTML = `当前的路由为${window.location.hash.slice(1)}`
    })
</script>

</html>

2.基于history实现的BrowserRouter,通过onpopstate事件和自定义的onpushstate事件实现 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hash路由</title>
</head>

<body>
    <div id="root" style="border:3px solid red;height:200px"> </div>
    <button onclick="push('/a')">/a</button>
    <button onclick="push('/b')">/b</button>
    <button onclick="push('/c')">/c</button>
    <script>
        let container = document.getElementById('root');
        //监听弹出状态的事件 浏览器上的后退按钮
        window.onpopstate = function (event) {
            //console.log(event);
            container.innerHTML = event.state.to;
        }
        // 自定义实现压栈状态的事件,这个事件window上是没有的
        function push(to) {
            // 参数一 状态
            // 参数二 标题 没有用到
            // 参数三 跳转的路径
            window.history.pushState({to},null,to)
        }
        // 覆写window.history.pushState方法
        // 1.先保存一下原有的方法
        const pushState = window.history.pushState;
        // 2.覆写
        window.history.pushState = function(state,title,url){
            // 3.调用系统的该方法
            pushState.call(window.history,state,title,url);
            // 4.调用自定义的onpushstate事件
            window.onpushstate(state,title,url)
        }
        // 5.将事件定义在window属性上 浏览器的前进按钮
        window.onpushstate = function(state,title,url) {
            container.innerHTML = state.to || url
        }
    </script>
</body>

</html>

3.实现路由的方式就上面两种,不论是angular、vue还是React都是这样实现的(一通百通,后面再出现什么框架,也离不开这两种)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值