【问题标题】:How to remove query param with react hooks?如何使用反应挂钩删除查询参数?
【发布时间】:2020-09-13 20:11:03
【问题描述】:

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

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

有没有办法在功能组件中使用反应挂钩?

【问题讨论】:

    标签: reactjs react-router react-hooks


    【解决方案1】:

    是的,您可以使用来自 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 对象,该对象具有包含 URL 查询字符串的 search 属性,例如?error=occurred&amp;foo=bar" 可以使用URLSearchParams API 转换为对象(IE 不支持)。

    【讨论】:

    • 这不适用于类组件,我们如何在那里处理它。
    • 在类组件中,将useEffect 替换为componentDidMount,将useState 替换为this.state,将useHistory 替换为this.props.history + withRouter HOC。这应该适用于类组件。
    • 如果有人有兴趣,要与功能组件一起使用,我创建了一个库useClearParamsgithub.com/oyalhi/use-clear-params#readme
    猜你喜欢
    • 2020-04-04
    • 1970-01-01
    • 2020-05-02
    • 2021-07-16
    • 2022-07-16
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多