通过 <Link> 重新加载组件在反应路由器中 [英] Reload component via &lt;Link&gt; in React Router

查看:49
本文介绍了通过 <Link> 重新加载组件在反应路由器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现类似 facebook 的主页(即带有评论的帖子列表).

I'm trying to implement a facebook-like homepage (i.e. a list of posts with comments).

PostList 是负责加载帖子列表的组件(在其 componentDidMount() 中使用 fetch),它本身是组件 HomePage.

PostList is the component in charge of loading the post list (using fetch in its componentDidMount() ), itself being a child of the component HomePage.

我有另一个名为 NavBar 的导航栏组件,带有一个 组件(来自 react-router-dom)到我的 HomePage 组件('/')的路径.

I have another component for the navigation bar called NavBar with a <Link> component (from react-router-dom) to the route of my HomePage component ('/').

当我在'/'以外的任何页面上时,使用链接工作正常:路由器安装HomePage,然后PostList触发componentDidMount() 并显示新检索到的帖子.

When I'm on any page other than '/', using the link works fine: the Router mounts HomePage, and then PostList triggering the componentDidMount() and displaying the freshly retrieved posts.

但是当我已经在/"上时,链接什么也不做,因为我已经在/"上,但我希望它仍然重新加载我的组件 HomePage 以便它可以更新其帖子列表.

But when I'm already on '/' the Link does nothing because well I'm already on '/', but I'd like it to still reload my component HomePage so it can update its post list.

我该怎么做?

推荐答案

React 组件仅在给定不同的 props(或 state 更改时)才会重新渲染).
我遇到了与您类似的问题,我通过每次将 timestamp 道具传递给组件来解决它.那为我解决了这个问题.所以在你的 组件中,你定义了 Home 组件的路由,使用下面的代码:

A React component re-renders only when it is given different props (or when it's state changes).
I had an issue similar to yours, and I solved it by passing a timestamp prop to the component everytime. That solved the issue for me. So inside you <Router> component, where you define the route for Home component, use the following code:

<Route path='/' component={ (props) => (
  <Home timestamp={new Date().toString()} {...props} />
)}/>

这样,timestamp 属性会在后续点击时发生变化,并且每次您点击 时组件都会重新渲染.

This way, the timestamp prop changes on subsequent clicks, and the component re-renders everytime you click the <Link>.

这篇关于通过 <Link> 重新加载组件在反应路由器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆