简体   繁体   English

反应路由器链接到具有不同 URL 的相同组件不重新渲染

[英]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.我有一个名为 Posts 的组件,它列出了博客中的所有帖子。 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.我有围绕帖子用户名的链接,这些链接仅使用不同的 URL 链接到相同的(帖子)组件,其中包含用于查询帖子的用户 ID。 The problem is that the Posts component will not re-render upon visiting this URL, although the URL in the browser changes accordingly.问题是 Posts 组件在访问此 URL 时不会重新呈现,尽管浏览器中的 URL 会相应更改。

Routes in App.js: App.js 中的路由:

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

Links in Posts.js 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.我还看到了一个“强制重新渲染”代码片段,但它是针对以前版本的 React Router 的。

How can I force the rendering of the Posts component in React Router v6?如何在 React Router v6 中强制渲染 Posts 组件?

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>而不是<Link>可能会起作用。

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

If Posts is rendered by a route that has changing route params如果Posts由具有更改路由参数的路由呈现

<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.Posts中使用useParams挂钩来访问user_id路由匹配参数,并使用依赖于user_iduseEffect挂钩来运行/重新运行任何逻辑。

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.如果Posts是 class 组件,则将其转换为 function 组件以便它可以使用 React 钩子,或者创建一个包装器组件或新的withRouter 替换以使用钩子并注入params作为道具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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