【问题标题】:React router with blog like functionality [duplicate]具有类似博客功能的反应路由器[重复]
【发布时间】:2019-06-12 21:38:21
【问题描述】:

我正在我当前的网站上实现一个博客。

我有一个这个作为我的路由器

<Router history={history}>
  <Switch>
    <Route exact path="/" component={Homepage} />
    <Route exact path="/case-studies" component={CaseStudies} />
    <Route path="/case-studies/:id" component={CaseStudiesSingle} />
    <Route path="/about" component={About} />
    <Route exact path="/blog" component={Blog} />
    <Route path="/blog/:id" component={BlogSingle} />
    <Route path="/contact-us" component={ContactUs} />
    <Route render={ () => <h1>Page not found</h1> } />
  </Switch>
</Router>

因此,通过将“exact”放在“/blog”和“/case-studies”上,一切正常,然后我可以转到单个页面。问题出在我的博客上,我有一个“最近的帖子”部分,但是当我在这个页面上“http://mysite.co.uk/blog/the-city-and-its-architecture”时,我不能去另一个像这样的博客帖子“http://mysite.co.uk//blog/photographer-and-designers”。我可以看到 url 发生变化,但我无法导航到另一个“BlogSingle 组件,因为我已经在上面了。有什么建议吗?

非常感谢!

【问题讨论】:

  • 访问该 URL 时收到 404
  • @GonFreecss 能贴出组件BlogSingle的代码吗?

标签: reactjs react-router router


【解决方案1】:
<Route path="/blog/:id" component={BlogSingle} />

对于此路由,因为只有一个参数在更改,而路由保持不变,所以您的组件将保持挂载状态。如果在BlogSingle 中,您有逻辑来确定componentDidMount 显示的内容,则需要将该逻辑放入componentDidUpdate 中,并在路由通过的match 道具上的参数更改时正确更新组件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 2018-10-18
    • 2019-10-02
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    相关资源
    最近更新 更多