[英]How to re-render a React Component Upon re-direct
我正在创建SoundCloud的克隆,当我从歌曲页面删除歌曲时,我想重定向到歌曲索引组件(/ discover页面)。
删除后我可以成功地重定向到那里,但是索引页面显示为空,直到刷新为止,然后就提取了歌曲。 我尝试过在index.page上使用ComponentDidUpdate在history.location不同但又没有成功的情况下再次获取歌曲。
//Song Delete Component
handleDelete() {
this.props.removeSong(this.props.songId)
this.props.history.push("/discover");
}
//Song Index Component
componentDidUpdate(prevProps) {
if (this.props.history.location.pathname !==
prevProps.location.pathname) {
this.props.fetchSongs();
}
}
当您重定向到新组件/路由时,该组件将重新安装到屏幕上。 您应该使用componentDidMount()
代替;
componentDidMount() {
this.props.fetchSongs();
}
刚刚了解到您的第二页实际上是一个模式,您执行了action-creator
并在其中重定向。 在那种情况下, Discover
组件实际上可能尚未从屏幕上卸载,因此为什么componentDidMount()
无法执行。 但是componentDidUpdate(
)应该仍然有效,让我们对其进行重构
因此,在“发现组件”中,尝试执行以下操作:
componentDidUpdate(prevProps){
if(this.props.songsOrNameOfReducerKey !== prevProps.songsOrNameOfReducerKey){
this.props.fetchSongs()
}
}
this.props.songsOrNameOfReducerKey
仅指保存更新后的歌曲列表的redux状态-可以作为组件中的prop来使用。 我们将更新后的列表与之前的列表进行比较,如果有差异,我们将执行您的操作创建者。 确保通过mapStateToProps()
将redux
连接到组件以获得该状态值。 用您定义的密钥替换songsOrNameOfReducerKey
。
从列表中删除歌曲时,它应该为Discover组件提供新的道具,从而触发componentDidUpdate()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.