在 React Router 中,使用浏览器历史推送时如何传递路由参数?
Posted
技术标签:
【中文标题】在 React Router 中,使用浏览器历史推送时如何传递路由参数?【英文标题】:In React Router, how do you pass route parameters when using browser history push? 【发布时间】:2016-12-05 08:25:08 【问题描述】:使用较新版本的 React Router,如果使用 browserHistory.push() 进行转换,如何将参数传递给要转换的路由?如果 browserHistory 不允许,我愿意使用其他方式进行转换。我看到在 React Router 中我最顶层的子组件中有 this.props.routeParams 但我似乎无法在转换时从上一个路由中填充我想要的值。
【问题讨论】:
【参考方案1】:现在你会做这样的事情
history.push(
pathname: '/about',
search: '?the=search',
state: some: 'state'
)
这是API documentation的链接
【讨论】:
从props获取的location
对象内
在下一页使用this.props.location.state.some访问状态
这在 React Router V4 中仍然有效吗?【参考方案2】:
对于 react router v4,我们可以这样做:
const history = useHistory();
history.push(
pathname: "/create-opinion/"+user,
state: username:userName
;
并简单地从其他组件中获取它:
const history = useHistory();
然后获取用户名:
const username = history.location.state.username;
别忘了从 react-router-dom 导入 useHistory
如果你还没有安装 react-router-dom 输入:
$ npm install --save react-router-dom
【讨论】:
【参考方案3】:如果要传递路径参数,可以按如下方式进行。我正在使用示例组件 Merchant。
定义路线
<Route exact path="/merchant/:id" render=(props) => <Merchant id=props.match.params.id/> />
定义历史
const history = createBrowserHistory(
basename:''
)
使用参数添加到历史记录
history.push(`/merchant/$id`)
【讨论】:
以上是关于在 React Router 中,使用浏览器历史推送时如何传递路由参数?的主要内容,如果未能解决你的问题,请参考以下文章
在 React Router 中,使用浏览器历史推送时如何传递路由参数?
使用 react-router-dom,如何从 React 组件外部访问浏览器历史对象?