react-router 只變 link 不更新內容的問題的解決 記錄

React + Redux + node.js 的項目

之前遇到類似的問題,是這種情況:

用 withRouter() 解決

Blocked Updates

Generally, React Router and Redux work just fine together. Occasionally though, an app can have a component that doesn’t update when the location changes (child routes or active nav links don’t update).
This happens if:
1. The component is connected to redux via connect()(Comp).
2. The component is not a “route component”, meaning it is not rendered like so:
The problem is that Redux implements shouldComponentUpdate and there’s no indication that anything has changed if it isn’t receiving props from the router. This is straightforward to fix. Find where you connect your component and wrap it in withRouter.
// before
export default connect(mapStateToProps)(Something)

// after
import { withRouter } from ‘react-router-dom’
export default withRouter(connect(mapStateToProps)(Something))

這次不一樣。

結構

  • Route
    • 檢測權限的高階組件
      • EpisodeContainer
        • Episode
          • SideCatalogue (側邊視頻目錄)

點擊視頻目錄,EpisodeContainer 組件 render 函數執行,但 componentDidMount() 以及 will.. 都不執行。根據鏈接請求視頻的邏輯寫在其中,自然不會執行,頁面停止在之前的內容。刷新頁面,內容會更新。

相同的代碼,在下面情況中是正常的

  • Route
    • 檢測權限的高階組件
      • CourseContainer
        • Course
          • Catalogue (本節相關視頻目錄)

react-router 大概原理,是 link 修改鏈接;router 定義鏈接與組件的匹配關係。
該情況下,從渲染 CourseContainer 變成渲染 EpisodeContainer ,後者的裝載過程的生命週期函數會執行。

而之前的情況是,本來就在 EpisodeContainer 裏,點擊鏈接,route 制定匹配的渲染的還是 EpisodeContainer,所以裝載過程的生命週期函數不執行。

對策:

只要父組件的render被調用,render….. 深入淺出 p30

此處,組件的props發送了改變,自然會調用該生命週期函數。
加上條件判斷,只有link變化後才執行邏輯,防止出現 props變化 => 執行=>props變化 => 執行 的死循環。

  componentWillReceiveProps() {
    if (this.props.history.location !== this.props.location) {
      let params = this.props.history.location.pathname.split('/')
      const [ , courseName, episodeName] = params
      this.props.fetchEpisode({courseName, episodeName})
    }
  }

通過數組解構賦值,點擊那個 link ,就向後臺請求相關的內容,從而實現新內容的渲染。

發佈了49 篇原創文章 · 獲贊 40 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章