天天看點

React Js Router 擷取位址欄url參數

本文出自:

http://blog.csdn.net/wyk304443164

有兩種方式擷取:請用的第二種

/**
 * 擷取url位址
 * @param name
 */

common.getQueryString = function (name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr().match(reg);
    if (r !== null) return unescape(r[]);
    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,需要用下面的那個方法,我已經做了處理,如果能用後面的就用後面的,用不了就前面的。因為咱們路由跳轉的時候,參數都是加在#後面的。

繼續閱讀