第一組讀書會 3-1 ~ 3-2 #31
steven4program
started this conversation in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
《React 進化思維》3-1 ~ 3-2 讀書會筆記
3-1 章節觀念自我檢測
Q: 為什麼 React 並沒有而且也不需要子 component 向上溝通父 component 的專門機制?
A: 透過 React 的核心機制:
因爲 setState 的函示可以透過 props 向下傳遞給子 component,所以在子 component 呼叫父 component 傳下來的 setState 時也會觸發 state 定義處的父 component re-render。而因為 React re-render 的特性,父 component re-render 後會連帶觸發子 component 以新版本的 props 去 re-render。
Q: 如何在子 component 中觸發更新父 component 的 state 資料?
A: 子 component 取得從父 component props 傳遞下來的 setState 函式(或是包含呼叫此 setState 的自定義函式),並在希望觸發父 component 資料更新的地方呼叫他。
3-2 章節觀念自我檢測
Q: 什麼是 Batch update?
A: React 會將一個事件中的所有 state update 統一在一個 rendering 去執行並 update DOM,這樣的好處是可以減少 component re-render 的次數。而這一個事件可能是一個 event handling 中,或是一個非同步(React v18 後支援)的操作中如 promise, setTimeout or setInterval. 處理的方式如下:
Q: 如果想要手動指定某些 setState 方法的呼叫不要 batch update 時,可以怎麼做?
A: 使用 flushSync() (React v18後提供),將 state update function 放入這個 flushSync 的 callback 函式中,React 就會以同步的方式立即性的觸發 component 的 re-render,並完成 actual DOM 的更新。然而在同一個事件中使用 flushSync, 在其執行完之後且仍在同一事件中時去讀取 state 的值,會發現 state 仍是事件前的值,因為在同一次 render 中, state 的值是永遠不變的。
可能會使用到 flushSync 的時機:
過多使用 flushSync 可能產生的問題:
Q: 什麼是 updater function?比起直接指定新的 state 值來說有什麼好處?
A: 在 React functional component 中 updater function 就是在 useState Hook 中更新 state 的一種語法函式。update function 在更新 state 時會取 state 舊有的值作為參數,然後必須回傳一個新值,主要的作用是以目前當下的原資料經過計算後產生新的資料,而非直接取代為某個值。
使用 Updater function 的好處:
Zet 補充
Q: 在所有情境下都適用 updater function 嗎?
A: 不是所有情境下都適用 updater function,使用 updater function 時,因為多取了一個 previous state 值,多少也增加了程式的複雜性與負載,在大多數狀況下的影響非常微小,但當在高度重視效能的情況下時,可能就會產生差異。
直接使用取代賦值優於 updater function 的情形:
Beta Was this translation helpful? Give feedback.
All reactions