React Js Router 获取地址栏url参数

本文介绍了一种用于从前端页面URL中获取查询参数的方法,并提供了一个改进版本以应对使用hashHistory的情况。通过两种不同的函数实现,确保了在各种路由配置下都能有效获取所需的参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文出自:

http://blog.youkuaiyun.com/wyk304443164

有两种方式获取:请用的第二种

/**
 * 获取url地址
 * @param name
 */

common.getQueryString = function (name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r !== null) return unescape(r[2]);
    return null;
};

/**
 * 获取url地址--NEW ,如果该方法获取不到会重新用上面的方法获取
 * @param _that
 * @param name
 * @returns {*}
 */

common.localQuery = function (_that, name) {
    let value = '';
    if (!this.isEmpty(_that) &&
        !this.isEmpty(_that.props) &&
        !this.isEmpty(_that.props.location) &&
        !this.isEmpty(_that.props.location.query)) {
        value = _that.props.location.query[name];
    }
    if (this.isEmpty(value)) {
        value = this.getQueryString(name);
    }
    return value;
};
/**
 * 判断是不是空的或者undefined
 * @param obj
 * @returns {boolean}
 */

common.isNull = function (obj) {
    return obj === null || typeof obj === 'undefined' || obj === undefined;
};

/**
 * 判断是不是空的字符串
 * @param obj
 * @returns {boolean}
 */

common.isEmpty = function (obj) {
    return this.isNull(obj) || obj === '';
};

使用:

common.localQuery(this, 'id')

如果用了hashHistory的话,后面会默认带一个 # 号,很明显,你不能删掉他,这时上面那个方法就不能获取到#/path?id=111 ,这边的id,需要用下面的那个方法,我已经做了处理,如果能用后面的就用后面的,用不了就前面的。因为咱们路由跳转的时候,参数都是加在#后面的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值