[英]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.