LiuL0703 / blog

https://liul0703.github.io
38 stars 11 forks source link

React一些细节的理解整理汇总 #39

Open LiuL0703 opened 4 years ago

LiuL0703 commented 4 years ago

React为什么不应该在componentWillMount阶段获取数据

This is problematic both server rendering (where the external data won’t be used) and the upcoming async rendering mode (where the request might be initiated multiple times). There is a common misconception that fetching in componentWillMount lets you avoid the first empty rendering state. In practice this was never true because React has always executed render immediately after componentWillMount. If the data is not available by the time componentWillMount fires, the first render will still show a loading state regardless of where you initiate the fetch. This is why moving the fetch to componentDidMount has no perceptible effect in the vast majority of cases.

为什么React的getDerivedStateFromProps方法是static ?

to help ensure purity which is important because it fires during interruptible phase ----- by Dan

This proposal is intended to reduce the risk of writing async-compatible React components. Choosing lifecycle method names that have a clearer, more limited purpose. Making certain lifecycles static to prevent unsafe access of instance properties. ----- react-rfc

why-is-getderivedstatefromprops-is-a-static-method

Reconciliation/ Render phase 和 Commit phase

Reconciliation / Render phase: React builds the work in progress tree and finds out the changes it needs to make without flushing them to the renderer. This is interruptible.

Commit phase: all the changes are flushed to DOM. This is uninterruptible.

useEffect vs useLayoutEffect

useLayoutEffect: If you need to mutate the DOM and/or DO need to perform measurements useLayoutEffect fires synchronously after all DOM mutations but before Paint phase. Use this to read layout(styles or layout information) from the DOM and then perform blocking custom DOM mutations based on layout.

useEffect: If you don't need to interact with the DOM at all or your DOM changes are unobservable (seriously, most of the time you should use this). useEffect runs after the render is committed to the screen i.e. after Layout and Paint phase. Use this whenever possible to avoid blocking visual updates

why is setState asynchronous?

  • Guaranteeing Internal Consistency
  • Enabling Concurrent Updates
  • Performance optimization

RFClarification: why is setState asynchronous?

React中的 type $$typeof tag

... 待补充