在浏览器中更改URL的值,但不更改要呈现的React组件

时间:2018-10-05 16:31:48

标签: react-router

我有一个链接<Link to = "country/USA"/>

然后选择路线<Route path="country/:countryId" component={Country}/>

呈现组件“ 国家/地区”时,浏览器网址为

http://<domain>/country/USA

是否可以将浏览器网址的显示方式更改为http://<domain>/country,并且仅将 countryId 用作 Country 中的Route道具组件。

经历过

https://reacttraining.com/react-router/web/api/BrowserRouter https://github.com/ReactTraining/react-router

找不到任何有用的东西。

有什么建议吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

除非您可以接受USA作为查询字符串的一部分,否则React Router内无能为力(片段来自react-training网站)

<Link to={{
  pathname: '/courses',
  search: '?sort=name',
  hash: '#the-hash',
  state: { fromDashboard: true }
}}/>

另一个不涉及路由器的替代方法是让一个Container组件接收USA作为道具,然后以编程方式呈现所需的组件。我想说,对于要在URL中显示的有意义的内容来说,这样做太多了

已编辑

通过组件执行此操作的一种方法是:

<Route path="country/some-static-keyword" render={() => <Country countryId={this.props.countryId}/>}/>