【问题标题】:React router dynamic routes not generating as expected反应路由器动态路由未按预期生成
【发布时间】:2020-04-18 23:10:32
【问题描述】:

我在我的项目中使用 react-router-dom 和 webpack。 当用户根据日期和ID点击某个链接时,它会将他们带到另一个页面。

我的路线:

 <Switch>
  <Route path="/" exact render={Home} />
  <Route exact path="/surveys/:date" render={Main} />
  <Route path="/surveys/:date/:id" render={Survey} />
  <Route render={() => <h1>404: page not found</h1>} />
</Switch>

我希望路径看起来像这样surveys/june/123,它在第一次点击时运行良好。但问题是,当用户从侧边栏加载另一个调查时,url 不会更改为surveys/june/124,而是更改为surveys/june/123/124,之后会更改为surveys/june/123/125,依此类推。例如,第一个加载的 id 始终保留在 url 中。

我试过了:

<Link to={`${match.url}/${id}`} />

path-to-regexp

const setPath = compile(match.path);
const newPath = setPath({
      ...match.params,
      id: id,
});

它们都不起作用。我做错了什么?

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    因为您每次都会获得匹配的 URL。 在您的第一次尝试中,您告诉 react 获取匹配的 URL 并为其添加一个 id。 如果我们假设 {match.url} 给我们 'surveys/june' 然后我们将 id 解析为它: 然后我们得到调查/六月/123 但是当从侧边栏 {match.url} 再次单击链接时,我们会得到“surveys/june/123”而不是“survey/june”,您再次将其解析为 id,最终产生您得到的结果。 我希望这对你来说很清楚 一个简单的解决方案是以这种方式使用链接:

    <Link to={`surveys/${date}/${id}`} />
    

    【讨论】:

    • 这样URL就变成surveys/:date/surveys/:date/id
    • 能否分享您使用链接的整个组件
    【解决方案2】:

    match.url 包含参数,match.path 不包含参数。

    这样做

    <Link to={`/${match.path}/${match.params.date}/${id}`} />
    

    https://reacttraining.com/react-router/core/api/match

    path - (string) 用于匹配的路径模式。对建筑有用 嵌套s

    url - (string) URL 的匹配部分。有用 用于构建嵌套 s

    【讨论】:

    • 日期不会在 url 中呈现,它只是 :datesurveys/:date/123
    • 好的 - 使用这个&lt;Link to={/${match.path}/${match.params.date}/${id}} /&gt; .. 我已经更新了答案
    猜你喜欢
    • 2021-10-14
    • 2012-10-04
    • 2021-02-05
    • 2019-05-27
    • 2019-08-09
    • 2016-07-19
    • 2023-03-30
    • 1970-01-01
    • 2016-02-24
    相关资源
    最近更新 更多