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

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

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


当前回答

你可以使用钩子useHistory 确保你使用的是基于函数的组件 在顶部导入这个

import {useHistory} from "react-router-dom"

在你的组件中,

const history = useHistory()
history.push({
    pathname: window.location.pathname,
    search: '?color=blue'
})

其他回答

对于React Router v6+,只需使用新的useSearchParams钩子(特别是setSearchParams):

const [searchParams, setSearchParams] = useSearchParams()

setSearchParams(`?${new URLSearchParams({ paramName: 'whatever' })}`)

对于React Router v5使用useHistory:

const history = useHistory()

history.push({
    pathname: '/the-path',
    search: `?${new URLSearchParams({ paramName: 'whatever' })}`
})

URLSearchParams只是一个可选的方便助手。

我更喜欢你使用下面的ES6风格的函数:

getQueryStringParams = query => {
    return query
        ? (/^[?#]/.test(query) ? query.slice(1) : query)
            .split('&')
            .reduce((params, param) => {
                    let [key, value] = param.split('=');
                    params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
                    return params;
                }, {}
            )
        : {}
};
// 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.3

const addQuery = (key, value) => {
  let pathname = props.location.pathname;
  // returns path: '/app/books'
  let searchParams = new URLSearchParams(props.location.search);
  // returns the existing query string: '?type=fiction&author=fahid'
  searchParams.set(key, value);
  this.props.history.push({
    pathname: pathname,
    search: searchParams.toString()
  });
};

const removeQuery = (key) => {
  let pathname = props.location.pathname;
  // returns path: '/app/books'
  let searchParams = new URLSearchParams(props.location.search);
  // returns the existing query string: '?type=fiction&author=fahid'
  searchParams.delete(key);
  this.props.history.push({
    pathname: pathname,
    search: searchParams.toString()
  });
};
function SomeComponent({ location }) {
  return <div>
    <button onClick={ () => addQuery('book', 'react')}>search react books</button>
    <button onClick={ () => removeQuery('book')}>remove search</button>
  </div>;
}

要了解更多关于URLSearchParams:

var paramsString = "q=URLUtils.searchParams&topic=api";
var searchParams = new URLSearchParams(paramsString);

//Iterate the search parameters.
for (let p of searchParams) {
  console.log(p);
}

searchParams.has("topic") === true; // true
searchParams.get("topic") === "api"; // true
searchParams.getAll("topic"); // ["api"]
searchParams.get("foo") === null; // true
searchParams.append("topic", "webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
searchParams.set("topic", "More webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
searchParams.delete("topic");
searchParams.toString(); // "q=URLUtils.searchParams"

就像@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 });