Javascript 路由器已更改,但组件未重新加载
我正在使用react路由器v4和redux。我有一个类似这样的事件Javascript 路由器已更改,但组件未重新加载,javascript,reactjs,ecmascript-6,redux,Javascript,Reactjs,Ecmascript 6,Redux,我正在使用react路由器v4和redux。我有一个类似这样的事件 //src/App/components/common/Notifications onCommentClick = (id) => { this.props.history.push(`/dashboard/${id}`) } 它会改变浏览器的url,我想我的路线设置正确 //src/App/containers/dashboard/user/NotificationDetail renderUserRoute
//src/App/components/common/Notifications
onCommentClick = (id) => {
this.props.history.push(`/dashboard/${id}`)
}
它会改变浏览器的url,我想我的路线设置正确
//src/App/containers/dashboard/user/NotificationDetail
renderUserRoute() {
return (
<Switch>
<Route exact path="/dashboard" component={UserAreaGuarded} />
<Route exact path="/dashboard/:id" component={NotificationDetail} />
</Switch>
)
}
//src/App/containers/dashboard/user/NotificationDetail
renderUserRoute(){
返回(
)
}
但问题是redux似乎没有重新发布我的容器组件,我需要刷新以获得正确的内容
我创建了一个repo只是为了演示这个问题,因为这个问题被困了这么久,找不到任何线索为什么它不重新提交。问题不在于路由器,组件只在中调用
fetchNotification
。与您一样,NotificationDetail
route组件只装载一次,然后在每次重新渲染时更新
有两种方法可以解决这个问题
NotificationDetail
中,执行componentdiddupdate
中的fetchNotification
操作,而不是componentdidMount
,只需重命名该方法即可。这种方法更好dashboard\index.js
中的component
prop的值:
renderUserRoute() {
return (
<Switch>
<Route exact path="/dashboard" component={UserAreaGuarded} />
<Route exact
path="/dashboard/:id"
component={props => <NotificationDetail {...props} />} />
</Switch>
)
}
renderUserRoute(){
返回(
} />
)
}
这将使React Router在每次路由更改时都呈现一个新的路由组件。显然,这在性能上存在问题Notification.js
中添加一个key={i}
来修复可怕的,数组或迭代器中的每个子级都应该有一个唯一的“key”属性。
警告
希望这有帮助。据我所知,您需要使用
shouldcomponentupdate
,因为React只是对道具进行了一次粗略的检查,所以它认为没有任何变化。您将看到,props.location.pathname
将在每次路由更改时更改,因此您可以使用它来强制重新渲染。是否尝试将状态与路径一起推<代码>历史。推送(路径,reduxState)Redux不应该在这里起作用,因为React路由器将根据历史更改处理更新。我的猜测是开关组件可能导致了这种情况。由于路由路径不模糊,请尝试移除交换机。与github repo链接相比,更喜欢codesandbox示例(如果可能的话),这会使实验更容易。@ChrisR为什么要推reduxState?“它从哪里来?”沙盒无法读取我的回购协议。据我所知,要渲染一个组件需要切换,这是有原因的。