簡體   English   中英

即使該組件的 props 或 state 沒有改變,React shouldComponentUpdate() 也會被調用

[英]React shouldComponentUpdate() is called even when props or state for that component did not change

我在 React 組件中添加了生命周期方法

  shouldComponentUpdate(nextProps, nextState) {
    console.log(nextProps, nextState);
    console.log(this.props, this.state);

    return false;  
  },

我的問題是,即使 nextProps 和 nextState 與當前的 props 和 state 完全相同,也會在組件上調用此方法。 當我比較 nextProps 和 this.props 的 console.log 語句時,它們完全相同。 和國家一樣。

那么為什么要調用 shouldComponentUpdate 呢?

每當我更改父組件的狀態時都會調用它。 但是沒有任何道具或狀態在實際組件上發生變化。 那為什么叫它呢?

僅供參考,我正在使用 React 和 Meteor

進一步說明:

我想知道為什么首先調用函數shouldComponentUpdate 該組件的狀態或道具都沒有改變。 但是父組件的狀態正在改變。

shouldComponentUpdate的目的是指示是否應該調用render 在您的情況下,某些父組件已呈現並表示它也想呈現您的子組件的實例。

shouldComponentUpdate是您短路渲染並說“ shouldComponentUpdate ,這里沒有任何變化”的機會。

現在,對於您的問題,“既然沒有任何變化,為什么還要調用它”? React 本身不會比較新舊 props。 你可以得到一個 mixin 來為你做,(即PureRenderMixin ),但默認情況下 React 只讓渲染運行。

React 本身不進行比較的原因有幾個。 首先,與分析道具和狀態相比,跳過渲染的性能節省可以忽略不計。 由於 React 的渲染機制已經優化以避免不必要的 DOM 操作,因此可以假設組件需要更新並期望合理的性能。 其次,進行比較並不完全是直截了當的。 你的道具是原始的嗎?,不可變的?,數組?,復雜的對象?,是否需要進行深度比較?

React 的模型是“我們將默認呈現所有要求的內容。如果您想選擇退出性能,請繼續並通過實現shouldComponentUpdate告訴我們”。

React 會自動調用shouldComponentUpdate ,它在重新渲染過程開始之前觸發(在這種情況下是您的父組件)。所以自然會頻繁調用它。

此函數的默認實現返回 true,因此要停止重新渲染,您需要在此處返回 false:

  shouldComponentUpdate(nextProps, nextState) {
    console.log(nextProps, nextState);
    console.log(this.props, this.state);

    return false;  
  }

高級問題,React 頁面

因此,總而言之,React 通過允許用戶使用 shouldComponentUpdate 來縮短進程,從而避免了執行協調 DOM 子樹所需的昂貴 DOM 操作,

shouldComponentUpdate()每次都會被調用:

  • 每次重新渲染父組件都會更新道具。 這包括使用完全相同的 prop 值進行重新渲染的所有場景。
  • 通過調用setState()更新狀態(react 允許的唯一方法)。 這包括狀態值完全相同的所有場景。

有時,即使新值與舊值完全相同,讓重新渲染循環通過也是有用的。 例如,當您的組件通過 props 接收到用戶 ID(可以保持不變),並從某處獲取新消息並將它們置於狀態時。

此外,“shouldComponentUpdate()”作為一種單獨的方法來檢查更改並且僅在發生更改時才進行更新,這使得代碼具有良好的可維護性:

  • 制作沒有shouldComponentUpdate()的第一個版本,並確保相同的道具和狀態shouldComponentUpdate()導致呈現相同的結果。
  • 添加和調試shouldComponentUpdate()

調試接受輸入(狀態和道具)並呈現輸出的“狀態機”相對容易。 調試管理狀態更改的機器要困難得多。

shouldComponentUpdate() – Returns true or false value based on certain conditions. 
If you want your component to update, return true else return false. 
By default, it returns 

真的。

if(shouldComponentUpdate) {
     // then render() is called and update UI/view 
}else{
   // then render() is not called ....[Don't update UI]
}

shouldComponentUpdate方法返回布爾值,指定 React 是否應繼續渲染。

默認值為真。

何時使用 shouldComponentUpdate:當您希望您的組件在前一個狀態值等於下一個狀態值時不呈現

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM