我似乎找不到如何更新查询参数与反应路由器不使用<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函数真的是侦听查询更改的唯一方法吗?为什么不自动检测和响应查询更改-以参数更改的方式?
当前回答
使用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
}))
}
其他回答
// 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
}))
}
在hashHistory的push方法中,可以指定查询参数。例如,
history.push({
pathname: '/dresses',
search: '?color=blue'
})
or
history.push('/dresses?color=blue')
您可以查看这个存储库以获得有关使用历史记录的其他示例
约翰的答案是正确的。当我处理参数时,我还需要URLSearchParams接口:
this.props.history.push({
pathname: '/client',
search: "?" + new URLSearchParams({clientId: clientId}).toString()
})
你可能还需要用一个withRouter HOC来包装你的组件。export default with throuter (YourComponent);
你可以使用钩子useHistory 确保你使用的是基于函数的组件 在顶部导入这个
import {useHistory} from "react-router-dom"
在你的组件中,
const history = useHistory()
history.push({
pathname: window.location.pathname,
search: '?color=blue'
})