简体   繁体   中英

React Router Link to same component with different URL not re-rendering

I have a component called Posts that lists all posts in a blog. I have links around the post's usernames which link to the same (Posts) component only with a different URL containing a user id to query the posts with. The problem is that the Posts component will not re-render upon visiting this URL, although the URL in the browser changes accordingly.

Routes in App.js:

<Routes>
  <Route path='/' element={<Posts/>}/>
  <Route path='/user/:user_id/posts' element={<Posts/>}/>
</Routes>

Links in Posts.js

<Link to={`/user/${post.user.id}/posts`}>
  {post.user.username}
</Link>

I have tried various things including trying to add a key to the component but it didn't work. I also saw a "force re-render" code snippet but it was for a previous version of React Router.

How can I force the rendering of the Posts component in React Router v6?

I'm not sure but maybe this kind of code would work I think...?

<Routes>
  <Route path='/' element={props => <Posts {...props} />}/>
  <Route path='/user/:user_id/posts' element={props => <Posts {...props} />}/>
</Routes>

And if it does not works, maybe just using <a> instead of <Link> might be work.

<a href={`/user/${post.user.id}/posts`}>
  {post.user.username}
</a>

If Posts is rendered by a route that has changing route params

<Routes>
  <Route path='/' element={<Posts/>}/>
  <Route path='/user/:user_id/posts' element={<Posts/>}/>
</Routes>

then it should "listen" for changes to the route's match params.

In Posts use the useParams hook to access the user_id route match param, and use an useEffect hook with a dependency on user_id to run/rerun any logic.

import { useParams } from 'react-router-dom';

...

const { user_id } = useParams();

useEffect(() => {
  if (user_id) {
    // do something with user_id
  }
}, [user_id]);

If Posts is a class component, then either convert it to a function component so it can use React hooks, or create a wrapper component or a new withRouter replacement to use the hook and inject params as a prop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM