首页 > 解决方案 > 如何使用反应挂钩删除查询参数?

问题描述

我知道我们可以按照以下方式替换基于组件的类中的查询参数:

  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(), 
      });   
    }   
  }

有没有办法通过功能组件中的反应钩子来做到这一点?

标签: reactjsreact-routerreact-hooks

解决方案


是的,您可以使用来自 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"


推荐阅读