当在同一路径上访问时,反应路由器链接不会引起重新渲染 [英] react router Link doesn't cause rerender when visited on the same path
问题描述
我正在使用React Router v4,重新加载页面时遇到了一些问题(不是window.location.reload).我最好给出一个实际的用例来解释这个问题,我们以一个社交网络应用程序为例:
I'm using react router v4, had some issue reloading the page (not window.location.reload). I better give a real use case to explain the issue, we use a social network app as the example:
- 用户A评论了用户B的帖子,一条通知显示在用户B页面中.
- 用户B单击该通知,我们做了
this.props.history.push('/job/' + id')
,它起作用了,因此用户B转到了job/123
页面. - 用户A再次评论,新的通知出现在用户B页面中,而用户B仍保留在
job/123
页面上,他单击了通知链接并触发了this.props.history.push('/job' + id')
.但是他不会看到页面重新呈现,他没有看到最新评论,因为页面什么都不做.
- user A commented a post by user B, a notification appear in user B page.
- user B clicked on the notification, we do
this.props.history.push('/job/' + id')
, it worked, hence user B went tojob/123
page. - user A commented again, new notification appear in user B page, while user B still remain on the
job/123
page, he clicked on the notification link and triggeredthis.props.history.push('/job' + id')
. But he won't see the page rerender, he DID NOT see the latest comment because the page does nothing.
推荐答案
在许多情况下,这似乎是常见的情况.可以使用许多不同的方法来解决它.选中此这种方法对我来说更有意义.
It seems to be a common scenario in many cases. It can be tackled using many different approaches. Check this stackoverflow question. There are some good answers and findings. Personally this approach made more sense to me.
location.key
也会每次更改一次.要在您的/jod/:id
组件中的代码块下面测试此位置:
location.key
changes every single time whenever user tries to navigate between pages, even within the same route
. To test this place below block of code in you /jod/:id
component:
componentDidUpdate (prevProps) {
if (prevProps.location.key !== this.props.location.key) {
console.log("... prevProps.key", prevProps.location.key)
console.log("... this.props.key", this.props.location.key)
}
}
我也有同样的情况. componentDidUpdate
中的更新状态.之后,按预期工作.单击同一路线内的项目会更新状态并显示正确的信息.
I had this exact same situation. Updated state in componentDidUpdate
. After that worked as expected. Clicking on items within the same route updates state and displays correct info.
我假设(不确定您如何在/job/:id
中传递/更新注释),如果您在/job/:id
组件中设置了类似的内容,则应该起作用:
I assume (as not sure how you're passing/updating comments in /job/:id
) if you set something like this in your /job/:id
component should work:
componentDidUpdate (prevProps) {
if (prevProps.location.key !== this.props.location.key) {
this.setState({
comments: (((this.props || {}).location || {}).comments || {})
})
}
}
这篇关于当在同一路径上访问时,反应路由器链接不会引起重新渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!