我想获取搜索params并将params添加到URL,但每次都得到空数组。
示例url - http://localhost:3000/buildings?search_query=test&page=2
constructor(props) {
super(props);
const params: URLSearchParams = new URLSearchParams(this.props.location.search);
console.log(params); //Getting empty object {}
}发布于 2020-09-02 22:45:58
尝试
console.log(params.get("page"));它应该返回“2”。URLSearchParams在控制台中显示为空对象,并且不会显示所有值。不过,它确实允许您调用get函数。
否则,请确保this.props.location.search确实具有有效的函数。
new URL("http://localhost:3000/buildings?search_query=test&page=2").search确实返回了一个有效值,例如。
发布于 2021-05-07 17:50:29
我猜您使用react-router并将URL查询字符串附加到/buildings。所以this.props.location.search是空的。
history.push({
pathname: '/buildings?search_query=test&page=2',
});请在search属性中设置URL查询字符串。
history.push({
pathname: '/buildings',
search: '?search_query=test&page=2'
});发布于 2021-08-04 16:43:03
事实证明,当您在chrome dev控制台中执行此操作时,它会向控制台返回一个空对象,而不是以标准的方式显示具有多个键的对象。
params = new URLSearchParams(window.location.search)当您注销params时,您会期望它显示一个带有键的对象,但它没有。为了在控制台中实际看到它们,您需要使用循环对其进行迭代
for (let item of params) {
console.log('item: ', item)
}非常令人困惑,因为我期望它像一个普通的对象一样工作
https://stackoverflow.com/questions/63707870
复制相似问题