如何使用反应钩子删除查询参数?

Set*_*ine 12 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(), 
      });   
    }   
  }
Run Code Online (Sandbox Code Playgroud)

有没有办法在功能组件中使用反应钩子来做到这一点?

Vae*_*lyr 34

使用useSearchParams钩子。

import {useSearchParams} from 'react-router-dom';

export const App =() => {
  const [searchParams, setSearchParams] = useSearchParams();

  const removeErrorParam = () => {
    if (searchParams.has('error')) {
      searchParams.delete('error');
      setSearchParams(searchParams);
    }
  }

  return <button onClick={removeErrorParam}>Remove error param</button>
}
Run Code Online (Sandbox Code Playgroud)


Aje*_*hah 27

是的,您可以使用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</>
  )
}
Run Code Online (Sandbox Code Playgroud)

AsuseHistory()返回具有可用于替换历史堆栈中当前条目的函数的历史对象replace

useLocation()返回具有包含 URL 查询字符串的属性的位置对象,search例如?error=occurred&foo=bar"可以使用URLSearchParams API(IE 不支持)将其转换为对象。

  • 在react-router-dom v6中使用Navigate (3认同)