I'm trying to implement a facebook-like homepage (i.e. a list of posts with comments).
PostList is the component in charge of loading the post list (using fetch in its componentDidMount() ), itself being a child of the component 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 ('/').
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.
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.
How can I do it ?
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} />
)}/>
This way, the timestamp prop changes on subsequent clicks, and the component re-renders everytime you click the <Link>.
I was solving a similar problem today. I had route:
<Route exact path="/:id" render={({ match }) => (<MyComponent match={match} />)} />
and link which did not invoke reload if newId was same as rendered id:
<Link to={{ pathname: `/${newId} }} >Go</Link>
The simplest solution I found was adding new reload redirect (right under route):
<Redirect from="/:id/reload" to="/:id" />
and changing link for newId === id to
<Link to={{ pathname: `/${id}/reload` }} >Reload</Link>
I also found a solution with adding new route with added timestamp (like 1567430708808):
<Route exact path="/:id/:ts" render={({ match }) => (<MyComponent match={match} />)} />
and reading it from match object for hooks, but timestamp occurred in URL and it was not as nice as the redirect. I need to mention I use react-router 5.0.1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With