我似乎找不到如何更新查询参数与反应路由器不使用<Link/>。hashHistory.push(url)似乎没有注册查询参数,而且似乎不能将查询对象或任何东西作为第二个参数传递。
如何将url从/shop/Clothes/dresses更改为/shop/Clothes/dresses?color=blue在反应路由器没有使用<链接>?
onChange函数真的是侦听查询更改的唯一方法吗?为什么不自动检测和响应查询更改-以参数更改的方式?
我似乎找不到如何更新查询参数与反应路由器不使用<Link/>。hashHistory.push(url)似乎没有注册查询参数,而且似乎不能将查询对象或任何东西作为第二个参数传递。
如何将url从/shop/Clothes/dresses更改为/shop/Clothes/dresses?color=blue在反应路由器没有使用<链接>?
onChange函数真的是侦听查询更改的唯一方法吗?为什么不自动检测和响应查询更改-以参数更改的方式?
当前回答
约翰的答案是正确的。当我处理参数时,我还需要URLSearchParams接口:
this.props.history.push({
pathname: '/client',
search: "?" + new URLSearchParams({clientId: clientId}).toString()
})
你可能还需要用一个withRouter HOC来包装你的组件。export default with throuter (YourComponent);
其他回答
约翰的答案是正确的。当我处理参数时,我还需要URLSearchParams接口:
this.props.history.push({
pathname: '/client',
search: "?" + new URLSearchParams({clientId: clientId}).toString()
})
你可能还需要用一个withRouter HOC来包装你的组件。export default with throuter (YourComponent);
使用React Router V6,我们可以像这样实现它
import { useNavigate, createSearchParams } from 'react-router-dom';
/* In React Component */
const navigate = useNavigate();
const params = {
color: 'blue',
};
const options = {
pathname: '/shop/Clothes/dresses',
search: `?${createSearchParams(params)}`,
};
navigate(options, { replace: true });
React-router-dom v5解决方案
import { useHistory } from 'react-router-dom';
const history = useHistory(); // useHistory hook inside functional component
history.replace({search: (new URLSearchParams({activetab : 1})).toString()});
建议使用URLSearchParams,因为它可以在编码和解码查询参数时处理查询参数中的空格和特殊字符
new URLSearchParams({'active tab':1 }).toString() // 'active+tab=1'
new URLSearchParams('active+tab=1').get('active tab') // 1
// 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 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只是一个可选的方便助手。