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

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

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


当前回答

对于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"

其他回答

我做了一个简单的钩子来减轻工作。

让我们想象一下你的url是这样的: /搜索吗?起源=主页= 1

function useUrl(param: string) {

    const history = useHistory()
    const { search, pathname } = useLocation()
    const url = new URLSearchParams(search)

    const urlParam = url.get(param)
    const [value, setValue] = useState(urlParam !== null ? urlParam : '')

    function _setValue(val: string){
        url.set(param, val)
        history.replace({ pathname, search: url.toString() }); 
        setValue(val)
    }

    return [value, _setValue]
}

那么实际使用情况:

function SearchPage() {

    const [origin] = useUrl("origin")
    const [page, setPage] = useUrl("page")

    return (
        <div>
            <p>Return to: {origin}</p>
            <p>Current Page: {page}</p>
        </div>
    )
}

在hashHistory的push方法中,可以指定查询参数。例如,

history.push({
  pathname: '/dresses',
  search: '?color=blue'
})

or

history.push('/dresses?color=blue')

您可以查看这个存储库以获得有关使用历史记录的其他示例

DimitriDushkin在GitHub上写道:

import { browserHistory } from 'react-router';

/**
 * @param {Object} query
 */
export const addQuery = (query) => {
  const location = Object.assign({}, browserHistory.getCurrentLocation());

  Object.assign(location.query, query);
  // or simple replace location.query if you want to completely change params

  browserHistory.push(location);
};

/**
 * @param {...String} queryNames
 */
export const removeQuery = (...queryNames) => {
  const location = Object.assign({}, browserHistory.getCurrentLocation());
  queryNames.forEach(q => delete location.query[q]);
  browserHistory.push(location);
};

or

import { withRouter } from 'react-router';
import { addQuery, removeQuery } from '../../utils/utils-router';

function SomeComponent({ location }) {
  return <div style={{ backgroundColor: location.query.paintRed ? '#f00' : '#fff' }}>
    <button onClick={ () => addQuery({ paintRed: 1 })}>Paint red</button>
    <button onClick={ () => removeQuery('paintRed')}>Paint white</button>
  </div>;
}

export default withRouter(SomeComponent);

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

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

在你的组件中,

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

在我的例子中,输入输入字段输出到浏览器的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