【问题标题】:/path/:id not switching view when Link is to={"/path/" + slug}/path/:id 不切换视图时 Link 是 to={"/path/" + slug}
【发布时间】:2021-03-06 19:20:40
【问题描述】:

我正在尝试通过使用它的 slug 来显示一个特定的帖子。我通过将 Route 路径设置为 /journal:id 和 Link to={"/journal" + post.field.slug} 成功实现了这一点。然而,这不是我想要的 url 的样子。猜猜为什么 Route 无法识别添加的斜线?

            <Switch>
                <Route path='/journal' component={Journal} />
                <Route path='/journal/:id' component={SinglePost} />
                <Route path='/shop' component={Shop} />
                <Route path='/contact' component={Contact}/>
            </Switch>

当我单击 Journal 内应该显示 SinglePost 组件的链接时,URL 发生了变化,但视图没有改变,我仍然看到 Journal。这是链接:

        <Link
            className='posts__post'
            key={post.fields.slug}
            to={"/journal/" + post.fields.slug}
        >

【问题讨论】:

  • 什么不起作用?你能发布一个不起作用的结果吗
  • @Hakier 继续解决它。问题是 path='/journal' 覆盖了我的 path='/journal/:id'

标签: javascript react-router react-hooks slug


【解决方案1】:

如果您有多个具有公共部分的路径,例如 /journal/journal/:id(公共部分是 /journal),您应该将属性 exact 添加到较短的路径中,以便在仅部分匹配时不会停止搜索路径

    <Switch>
        <Route exact path='/journal' component={Journal} />
        <Route path='/journal/:id' component={SinglePost} />
        <Route path='/shop' component={Shop} />
        <Route path='/contact' component={Contact}/>
    </Switch>

【讨论】:

    猜你喜欢
    • 2022-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 2020-01-01
    相关资源
    最近更新 更多