我似乎找不到如何更新查询参数与反应路由器不使用<Link/>。hashHistory.push(url)似乎没有注册查询参数,而且似乎不能将查询对象或任何东西作为第二个参数传递。

如何将url从/shop/Clothes/dresses更改为/shop/Clothes/dresses?color=blue在反应路由器没有使用<链接>?

onChange函数真的是侦听查询更改的唯一方法吗?为什么不自动检测和响应查询更改-以参数更改的方式?


当前回答

就像@Craques解释的那样,我们可以使用替换功能,而不是每次更改都推送一个新路由。然而,在react-router的第6版中,useHistory()被useNavigate()取代,它只返回一个函数。你可以将选项传递给函数,以达到与旧的location.replace()相同的效果:

import { useLocation, useNavigate } from 'react-router-dom';
const to = { pathname: location.pathname, search: newParams.toString() };
navigate(to, { replace: true });

其他回答

在我的例子中,输入输入字段输出到浏览器的url作为查询字符串,使用React JS功能组件如下所示


import React, { useEffect, useState } from 'react'
import { useHistory } from 'react-router-dom'

const Search = () => {
  const [query, setQuery] = useState('')
  const history = useHistory()

  const onChange = (e) => {
    setQuery(e.target.value)
  }

  useEffect(() => {
    const params = new URLSearchParams()
    if (query) {
      params.append('name', query)
    } else {
      params.delete('name')
    }
    history.push({ search: params.toString() })
  }, [query, history])

  return <input type="text" value={query} onChange={onChange} />
}

export default Search


浏览器URL查询

/搜索吗?name = query_here

当你需要一个模块来轻松地解析你的查询字符串时,推荐使用query-string模块。

http://localhost:3000?token=xxx-xxx-xxx

componentWillMount() {
    var query = queryString.parse(this.props.location.search);
    if (query.token) {
        window.localStorage.setItem("jwt", query.token);
        store.dispatch(push("/"));
    }
}

在这里,我从Node.js服务器重定向回我的客户端后,成功的Google-Passport身份验证,这是重定向回令牌作为查询参数。

我用query-string模块解析它,保存它并更新url中的查询参数,从react-router-redux推送。

您可以使用replace功能,而不是在每次更改时推送一个新路由

import React from 'react';
import { useHistory, useLocation } from 'react-router';

const MyComponent = ()=>{
   const history = useHistory();
   const location = useLocation();

   const onChange=(event)=>{
     const {name, value} = event?.target;
     const params = new URLSearchParams({[name]: value });
     history.replace({ pathname: location.pathname, search: params.toString() });       
   }

   return <input name="search" onChange={onChange} />
}

这保留了历史,而不是在每一个变化上都推一条新的道路

更新- 2022年2月(V6)

正如Matrix Spielt指出的那样,useHistory被usenavate取代来进行更改。还有一个方便的方法叫做useSearchParams,我只需要阅读文档,没有运行这个,但这应该可以工作

import React from 'react';
import { useSearchParams } from 'react-router-dom';
// import from react-router should also work but following docs
// import { useSearchParams } from 'react-router';

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

   const onChange=(event)=>{
     const {name, value} = event?.target;
     setSearchParams({[name]: value})       
   }

   return <input name="search" onChange={onChange} />
}
// react-router-dom v6

// import
import { useNavigate, createSearchParams } from 'react-router-dom';

// useSearchParams hook
const [searchParams, setSearchParams] = useSearchParams();

// usage
const params: URLSearchParams = new URLSearchParams();
params.id = '123';
params.color = 'white';

// set new parameters
setSearchParams(params);

! !当心!!这将只更新当前页面上的查询参数,但您将无法导航回(浏览器返回btn)到以前的路由,因为此选项不会更改历史记录。要使此行为到位,请检查之前的答案:https://stackoverflow.com/users/6160270/rakesh-sharma的答案

使用react-router v4、redux-thunk和react-router-redux(5.0.0-alpha.6)包的示例。

当用户使用搜索功能时,我希望他能够为相同的查询发送url链接给同事。

import { push } from 'react-router-redux';
import qs from 'query-string';

export const search = () => (dispatch) => {
    const query = { firstName: 'John', lastName: 'Doe' };

    //API call to retrieve records
    //...

    const searchString = qs.stringify(query);

    dispatch(push({
        search: searchString
    }))
}