JS的history和location用法;react路由的history对象的插件history的使用介绍

一、什么是location

首先介绍的是location对象,location是BOM对象中最常用的一个对象之一,它提供了与当前窗口中加载的文档的有关的信息,还提供了一些导航的功能。说到这里,其实location是一个非常的特别的对象,因为window.location===document.location.另外location对解析URL非常的有帮助,下面看一下location的属性表。

http://www.google.com:8080/loanOrder/detail?orderId=1236#type

 

属性名例子说明
hash"#type"设置或返回URL中的#后面的hash值,如果没有则为""
host"www.google.com:8080"设置或返回URL中的主机名称和端口号
hostName"www.google.com"设置或返回URL中的主机名称
href"http://www.google.com:8080/loanOrder/detail?orderId=1236#type"设置或返回完整的URL
pathname"/loanOrder/detail"设置或返回当前 URL 的路径部分
port"8080"设置或返回URL中的端口号,如果URL中没有端口号,则为""
protocol"http:"设置或返回当前 URL 的协议,通常是http:或https:
search"?orderId=1236"返回URL的查询字符串。这个字符串以"?"开头

JS中的用法:

1.查询字符串参数

function getArgsQuery() {
        //取得查询字符串并去掉"?"
        var searchStr=window.location.search.length>0?window.location.search.substring(1):"";
        //将每一项集成到数组中
        var searchStrArray=searchStr.length>0?searchStr.split("&"):[];
        //存储最后返回的对象
        var args={};
        searchStrArray.forEach(function (item) {
            //属性
            var name=decodeURIComponent(item.split("=")[0]);
            //值
            var value=decodeURIComponent(item.split("=")[1]);
            args[name]=value;
        });
        return args;
    }

2.改变浏览器的位置

1) window.location.reload() //重新加载页面

在调用reload()不传任何参数时,页面自上次请求以来并没有改变过,页面就会从游览器缓存中加载,如果传入参数true时,页面会强制从服务器重新加载。

例:
 window.location.reload()  //重新加载(有可能从缓存中加载)
 window.location.reload(true) //重新加载(从服务器重新加载)

2) window.location.assign(url); //加载新的文档

与 window.location.assign(url)效果一样的还有

 - window.location.href=url;
 - window.location=url;

3) window.location.replace(url); //用新文档替换当前文档

 

同样是加载新文档,区别就是window.location.assign(url)是可以从新文档再回到当前文档,但是window.location.replace(url)就不行了,用来实现过渡页面时非常好用,但是有些webview却是不支持的,比如小编在开发的钉钉上的微应用的时候就遇到这个,这时我们该如何做呢?下面就是我们讲到的history对象。

二、History 

History 对象最初设计来表示窗口的浏览历史。但出于隐私方面的原因,History 对象不再允许脚本访问已经访问过的实际 URL。唯一保持使用的功能只有 back()、forward() 和 go() 方法。

    
    window.history.go(-2);  //后退两页   
    window.history.go(-1);  //后退一页   
    window.history.go(1);   //前进一页
    window.history.go(2);   //前进两页
   
    window.history.back();//后退一页
    window.history.forward();//前进一页

1) window.history.pushState(stateObject,title,url )

将当前URL和history.state加入到history中,并用新的state和URL替换当前,不会造成页面刷新。

--参数解释
stateObject    //与要跳转到的URL对应的状态信息,没有特殊的情况下可以直接传{}
title       //现在大多数浏览器不支持或者忽略这个参数,我们在用的时候建议传一个空字符串
url            //这个参数提供了新历史纪录的地址,它不一定要是绝对地址,也可以是相对的,不可跨域

2) window.history.replaceState(stateObject,title,url)

用新的state和URL替换当前,不会造成页面刷新。

--参数解释
stateObject    //与要跳转到的URL对应的状态信息,没有特殊的情况下可以直接传{}
title       //现在大多数浏览器不支持或者忽略这个参数,我们在用的时候建议传一个空字符串
url            //这个参数提供了新历史纪录的地址,它不一定要是绝对地址,也可以是相对的,不可跨域

/*
    可能还有其他的方法,如果有欢迎留言交流
    这里我依旧拿https://www.lagou.com/gongsi/j35166.html举例
    打开控制台,输入下面这段代码。
*/
history.replaceState({name: "华为"}, "", "j87078.html");
window.location.reload();

/*
执行完之后,我们发现不能回退了,是不是就跟window.location.replace()实现同样的效果了。
*/

三、react路由的history对象的插件history的使用介绍

 

  1. history插件的使用

    history这个插件可以方便管理你的浏览记录
    cnpm install history --save
    import createHistory from 'history/createBrowserHistory'
  2. 三种方法

    有三种使用方式
        createBrowserHistory 现代浏览器使用
            createBrowserHistory({
                basename: '', // 基链接
                forceRefresh: false, // 是否强制刷新整个页面
                keyLength: 6, // location.key的长度
                getUserConfirmation: (message,callback) => callback(window.confirm(message)) // 跳转拦截函数
            })
        createMemoryHistory 手机端使用
            createMemoryHistory({
                initialEntries: ['/'], // 初始载入路径,和MemoryRouter中的initialEntries是一样的
                initialIndex: 0, // initialEntries初始载入索引
                keyLength: 6, // location.key的长度
                getUserConfirmation: null // 路由跳转拦截函数
            })
        createHashHistory 老版本浏览器使用,暂不介绍
  3. 基本使用功能

    const history = createHistory(); 创建历史对象
    const location = history.location; 获取location对象
    const unlisten = history.listen( (location, action) => {
        console.log(location,action)
        // location是location对象
        // action是动作名称,比如 "PUSH"
    } )
    history.push('/a', { some: 'state' }) // 强制跳转
    unlisten() // 监听解绑
  4. history对象

    属性:
        上面三种方法创建的history对象都有如下三个属性
            history.length 历史记录的条数
            history.location 历史记录中的location对象
            history.action 当前的历史记录是通过什么动作添加进来的,如 "PUSH"
        createMemoryHistory中提供了额外的两个属性
            history.index 当前历史记录的索引
            history.entries 历史记录
    方法
        listen方法
            history.listen( (location,action) => {
                console.log(location,action);
                // location就是window.location的一个子集
                // action可能的值,"PUSH", "REPLACE", "POP"
            } )
  5. 使用history实现跳转

    push    
        使用push可以将一条新的历史记录推送到历史堆栈中
        history.push('/a');
        history.push('/a',{name: 'yejiawei'});
        history.push({
            pathname: '/a',
            state: {
                name: 'yejiawei'
            }
        });
    replace方法和push方法使用形式一样,replace的作用是取代当前历史记录
    go,此方法用来前进或者倒退,history.go(-1);
    goBack,此方法用来回退,history.goBack();
    goForward,此方法用来前进,history.goForward();
    另外使用createMemoryHistory创建的history对象,有canGo方法,和go方法类似
  6. 使用history实现路由跳转警告

    const unblock = history.block('Do you want to leave?');
    上面这个用法,就是添加一个跳转提示信息,默认使用dom环境的window.confirm,所以如果使用非dom环境的createMemoryHistory就要使用getUserConfirmation方法实现
    另外,除了传递一个字符串提示信息以外,还可以添加函数
    const unblock = history.block( (location,action) => {
        return 'do you leave?'
    } )
    可以通过直接调用,unblock(); 实现方法解绑

react部分转自:

https://www.cnblogs.com/ye-hcj/p/7741742.html

以上来自自己疑问综合多篇文章整理。如有侵权联系删除,纯属学习笔记

  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React Router提供了一种使用`<Route>`组件的方法来监听路由变化。可以使用`componentDidUpdate`方法来检测路由变化,从而执行相应的操作。 以下是一个例子,展示如何在React Router中监听路由变化: ```javascript import React from 'react'; import { Route } from 'react-router-dom'; class App extends React.Component { componentDidUpdate(prevProps) { if (this.props.location !== prevProps.location) { // 路由已经变化 console.log('路由变化'); } } render() { return ( <div> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/contact" component={Contact} /> </div> ); } } ``` 如果想要监听`history.push/replaceState`,可以通过重写这些方法来实现: ```javascript const originalPush = history.push; history.push = function push(pathname, state) { originalPush.call(this, pathname, state); window.dispatchEvent(new Event('pushstate')); }; const originalReplace = history.replace; history.replace = function replace(pathname, state) { originalReplace.call(this, pathname, state); window.dispatchEvent(new Event('replacestate')); }; ``` 然后,可以通过监听`pushstate`和`replacestate`事件来检测状态的变化: ```javascript window.addEventListener('pushstate', function() { console.log('history.pushState 发生了变化'); }); window.addEventListener('replacestate', function() { console.log('history.replaceState 发生了变化'); }); ``` 如果想要监听`local/sessionStorage`的变化,可以使用`window.addEventListener`来监听相应事件: ```javascript window.addEventListener('storage', function(e) { if (e.key === 'mykey') { console.log('localStorage变化为:' + e.newValue); } }); ``` 同样的,可以使用`sessionStorage`来监听`sessionStorage`的变化。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值