2016-01-15 89 views
3

有人可以解釋一下到底發生了什麼我的下一個背景:陣營:componentWillUpdate

假設我有一個應用程序的組件(父),有的孩子部件假設索引,搜索,關於和這3個有自己的孩子。

當我在應用程序組件中調用componentWillUpdate時會發生什麼,新狀態/道具將會出現,但葉子(兒童)內會發生什麼,他們會重新渲染自己嗎?

假設我在應用程序的這個componentWillUpdate中覆蓋了DOM中的某些東西,並且我將在componentDidMount或componentWillMount中的葉子組件中的DOM中使用同樣的東西...哪個值將是最後一個?

+0

我建議你閱讀生命週期方法的文檔(https://facebook.github.io/react/docs/component-specs.html#lifecycle-methods)。我認爲這裏有很好的解釋。一般而言,您希望避免自己更改DOM,而是讓React儘可能地根據狀態變化呈現您的DOM。 – Mark

回答

5

首先,您不應該手動撥打componentWillUpdate。如果作爲其生命週期的一部分,則由React調用。

根據comment in ReactCompositeComponent.js這是在更新階段什麼hapens:

Update Phases: 
     - componentWillReceiveProps (only called if parent updated) 
     - shouldComponentUpdate 
      - componentWillUpdate 
      - render 
      - [children's constructors or receive props phases] 
      - componentDidUpdate 

正如你可以看到App.render渲染兒童copmonents之前被調用。

如果您想由於某種原因手動操作DOM,則componentWillUpdate不適合執行此操作。每次更新後使用componentDidUpdate或初始渲染後使用componentDidMount。父母的生命週期方法之前觸發兒童的componentDidUpdatecomponentDidMount