如何使用react挂钩删除查询参数?

时间:2020-05-26 21:55:01

标签: reactjs react-router react-hooks

我知道我们可以替换基于组件的类中的查询参数,具体做法如下:

  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钩子来做到这一点?

1 个答案:

答案 0 :(得分:5)

是的,您可以使用react-router中的useHistoryuseLocation钩子:


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不支持)将其转换为对象。