我使用以下代码从URL检索查询参数,但URLSearchParams返回一个空对象。
PS: uselocation.search返回正确的输出。
const stringdata = useLocation().search
const queryparameter = new URLSearchParams(stringdata)
console.log("query parameter :", queryparameter)
const query = queryparameter.get('q');
var url_string = `http://localhost:3000/recipes${query}`发布于 2021-12-25 09:41:26
您可以尝试在用户搜索参数上使用window.location.search。应该是这样的:
const queryParams = new URLSearchParams(window.location.search);
const query = queryParams.get('q');
let url_string = `http://localhost:3000/recipes${query}`;发布于 2022-04-17 17:17:02
search属性返回URL的querystring部分,包括问号(?)。
const queryParams = new URLSearchParams(window.location.search);然后,您需要检查queryparameter.get('q')是否存在,否则它将返回null并将null附加到url。
let query;
if(queryParameter.has('q')){
query = queryparameter.get('q');
}然后
var url_string = `http://localhost:3000/recipes/${query}`https://stackoverflow.com/questions/70478181
复制相似问题