reactjs - 如何使用反应挂钩删除查询参数?
问题描述
我知道我们可以按照以下方式替换基于组件的类中的查询参数:
componentDidMount() {
const { location, replace } = this.props;
const queryParams = new URLSearchParams(location.search);
if (queryParams.has('error')) {
this.setError(
'There was a problem.'
);
queryParams.delete('error');
replace({
search: queryParams.toString(),
});
}
}
有没有办法通过功能组件中的反应钩子来做到这一点?
解决方案
是的,您可以使用来自 react-router 的useHistory
&钩子:useLocation
import React, { useState, useEffect } from 'react'
import { useHistory, useLocation } from 'react-router-dom'
export default function Foo() {
const [error, setError] = useState('')
const location = useLocation()
const history = useHistory()
useEffect(() => {
const queryParams = new URLSearchParams(location.search)
if (queryParams.has('error')) {
setError('There was a problem.')
queryParams.delete('error')
history.replace({
search: queryParams.toString(),
})
}
}, [])
return (
<>Component</>
)
}
AsuseHistory()
返回历史对象,该对象具有replace
可用于替换历史堆栈上的当前条目的功能。
并useLocation()
返回具有包含 URL 查询字符串的属性的位置对象,例如,可以使用URLSearchParams API(IE 不支持)将其转换为对象。search
?error=occurred&foo=bar"
推荐阅读
- php - 为 mysql pdo 查询清理表单提交的数据
- r - 计算 R 中两个不同数据帧的两个时间戳之间的行数
- api - 为什么 Telethon 发送文件这么慢?
- python - 如何将 txt 文件导入到 ipickle 文件中?
- scrapy - 无法使用 scrapy 抓取页面网页的部分内容
- javascript - VueJs 不显示从 axios 承诺中获取的图像,然后将图像 url 放入 src
- java - 用数字而不是索引编辑arraylist
- java - 实现缓存框架(ehcache)以在服务器启动期间缓存 Lookupcode 和 Location 下拉值
- angular - 如何创建自定义原理图以创建新的角度项目和一些文件
- android - 如何在没有 READ_CALL_LOG 权限的情况下在 Android 9 中获取来电和去电号码?