【问题标题】:To change the value of the URL in the browser, but not the React component to be rendered改变浏览器中 URL 的值,而不是要渲染的 React 组件
【发布时间】:2019-03-11 05:07:17
【问题描述】:

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

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

当渲染组件“Country”时,浏览器Url为

http://<domain>/country/USA

有没有办法将浏览器Url的显示更改为http://&lt;domain&gt;/country,并且只有“countryId”作为Country组件中的Route props。

经历过

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

找不到任何有用的东西。

有什么建议吗?

谢谢!

【问题讨论】:

    标签: react-router


    【解决方案1】:

    除非您可以将 USA 作为查询字符串的一部分,否则您在 React Router 中无能为力(sn-p 来自 react-training 站点)

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

    另一个不涉及路由器的替代方法是拥有一个容器组件,该组件接收USA 作为道具,然后以编程方式呈现您想要的组件。我想说这对于在 URL 中显示有意义的东西来说工作量太大了

    已编辑

    一种通过组件实现的方法是这样的:

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

    【讨论】:

    • 感谢@tan-kim-loong 的回复。
    • 但它是项目要求,不在浏览器Url中显示Item的任何具体细节。所以基本上我需要这个路由到组件,但在浏览器 URL 中没有具体的细节(countryId)。
    猜你喜欢
    • 2021-10-03
    • 2021-10-21
    • 2020-02-08
    • 1970-01-01
    • 2015-08-04
    • 2021-05-17
    • 2020-07-05
    • 1970-01-01
    • 2021-07-20
    相关资源
    最近更新 更多