我知道我们可以替换基于组件的类中的查询参数,具体做法如下:
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钩子来做到这一点?
答案 0 :(得分:5)
是的,您可以使用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</>
)
}
useHistory()
返回history对象,该对象具有replace
函数,可用于替换历史记录堆栈上的当前条目。
然后useLocation()
返回location对象,该对象具有search
属性,其中包含URL查询字符串,例如?error=occurred&foo=bar"
可以使用URLSearchParams API(IE不支持)将其转换为对象。