不是反应的方式,但我相信这个单行函数可以帮助你:)
const getQueryParams = (query = null) => [...(new URLSearchParams(query||window.location.search||"")).entries()].reduce((a,[k,v])=>(a[k]=v,a),{});
或:
const getQueryParams = (query = null) => (query||window.location.search.replace('?','')).split('&').map(e=>e.split('=').map(decodeURIComponent)).reduce((r,[k,v])=>(r[k]=v,r),{});
或完整版:
const getQueryParams = (query = null) => {
return (
(query || window.location.search.replace("?", ""))
// get array of KeyValue pairs
.split("&")
// Decode values
.map((pair) => {
let [key, val] = pair.split("=");
return [key, decodeURIComponent(val || "")];
})
// array to object
.reduce((result, [key, val]) => {
result[key] = val;
return result;
}, {})
);
};
例子:
URL:…?= = 1 b =建发集团有限公司的测试
代码:
getQueryParams()
//=> {a: "1", b: "c", d: "test"}
getQueryParams('type=user&name=Jack&age=22')
//=> {type: "user", name: "Jack", age: "22" }