Please enable JavaScript.
Coggle requires JavaScript to display documents.
鐵人賽 React (基礎 (State and Lifecycle (State Updates May Be Asynchronous…
鐵人賽 React
基礎
安裝
-
- JSX using script tag with attribute text/bable
-
React Dev Tool
-
In most cases, instead of writing shouldComponentUpdate() by hand, you can inherit from React.PureComponent. It is equivalent to implementing shouldComponentUpdate() with a shallow comparison of current and previous props and state.
JSX
-
-
-
Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming convention instead of HTML attribute names.
-
components-and-props
When React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object “props”.
-
-
We recommend naming props from the component’s own point of view rather than the context in which it is being used.
-
State and Lifecycle
-
In applications with many components, it’s very important to free up resources taken by the components when they are destroyed.
We want to set up a timer whenever the Clock is rendered to the DOM for the first time. This is called “mounting” in React.
We also want to clear that timer whenever the DOM produced by the Clock is removed. This is called “unmounting” in React.
-
-
-
-
The Data Flows Down
This is commonly called a “top-down” or “unidirectional” data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.
Handling Events
React events are named using camelCase, rather than lowercase.
SyntheticEvent
The SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked
Conditional Rendering
Returning null from a component’s render method does not affect the firing of the component’s lifecycle methods. For instance componentDidUpdate will still be called.
Lists and Keys
We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state.
-
-
-
Forms
-
The textarea Tag
In React, a <textarea> uses a value attribute instead. This way, a form using a <textarea> can be written very similarly to a form that uses a single-line input
The select Tag
You can pass an array into the value attribute, allowing you to select multiple options in a select tag
Lifting State Up
In React, sharing state is accomplished by moving it up to the closest common ancestor of the components that need it
-
If something can be derived from either props or state, it probably shouldn’t be in the state.
-
Thinking In React
If you’re familiar with the concept of state, don’t use state at all to build this static version. State is reserved only for interactivity, that is, data that changes over time.
-
To build your app correctly, you first need to think of the minimal set of mutable state that your app needs. The key here is DRY: Don’t Repeat Yourself. Figure out the absolute minimal representation of the state your application needs and compute everything else you need on-demand.
Is it passed in from a parent via props? If so, it probably isn’t state.
Does it remain unchanged over time? If so, it probably isn’t state.
Can you compute it based on any other state or props in your component? If so, it isn’t state.
Advanced Guides
-
error boundaries only catch errors in the components below them in the tree. An error boundary can’t catch an error within itself.
-
-
HOC
There is one caveat to the above example: refs will not get passed through. That’s because ref is not a prop. Like key, it’s handled differently by React.
-
Context
-
-
The defaultValue argument is only used by a Consumer when it does not have a matching Provider above it in the tree.
-
Consumer Requires a function as a child. The function receives the current context value and returns a React node.
The propagation from Provider to its descendant Consumers is not subject to the shouldComponentUpdate method, so the Consumer is updated even when an ancestor component bails out of the update.
-
optimizing-performance
-
In most cases, instead of writing shouldComponentUpdate() by hand, you can inherit from React.PureComponent. It is equivalent to implementing shouldComponentUpdate() with a shallow comparison of current and previous props and state.
-
-
JSX in depth
When an element type starts with a lowercase letter, it refers to a built-in component like <div> or <span> and results in a string 'div' or 'span' passed to React.createElement. Types that start with a capital letter like <Foo /> compile to React.createElement(Foo) and correspond to a component defined or imported in your JavaScript file.
If you pass no value for a prop, it defaults to true.
Booleans, Null, and Undefined Are Ignored
ref
Forwarding Refs
-
Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.
There is one caveat to the above example: refs will not get passed through. That’s because ref is not a prop. Like key, it’s handled differently by React.
Refs and the DOM
-
-
When the ref attribute is used on an HTML element, the ref created in the constructor with React.createRef() receives the underlying DOM element as its current property.
When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current.
-
心得:當 ref 用在 DOM Element 和 Custom Component 時,效果會不同;用在 DOM 上, ref 是直接取得 DOM Element ;用在 Custom Component 上,是取得該 Component 的 Instance ,可以直接呼叫該 Component 的 method 。
You can, however, use the ref attribute inside a function component as long as you refer to a DOM element or a class component
-
Reconciliation
The key only has to be unique among its siblings, not globally unique.
The algorithm will not try to match subtrees of different component types. If you see yourself alternating between two component types with very similar output, you may want to make it the same type. In practice, we haven’t found this to be an issue.
Keys should be stable, predictable, and unique. Unstable keys (like those produced by Math.random()) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.
-
The developer can hint at which child elements may be stable across different renders with a key prop.
The diffing algorithm
Elements Of Different Types
當 root element type 不同時,會將舊的 tree 拆掉並重建新的。
當拆除 tree 時,舊的 DOM node 會被銷毀, Component 的實體會收到 ComponentWillUnmount 的事件;建立新的 tree 時, DOM node 會被插入到 DOM 中, Component 的實體將會收到 ComponentWillMoun 接著是 ComponentDidMount 的事件,任何與舊的 tree 有關的 state 將會遺失
任何在 root 下的 Component ,也會被卸載掉,且 state 也會被銷毀
DOM Elements Of The Same Type
當比較兩個相同 type 的 element 時, React 會查看兩者的 attributes ,保持底層的 DOM node ,只改變不同的 attributes 。
處理完畢後, React 會遞迴得處理子元素
Component Elements Of The Same Type
當 Component 更新時,實體會保持一樣,讓 state 在 render 間都會保持住。 React 更新底層 Component 實體的 prop ,以符合新的 element ,接著呼叫底層的 ComponentWillReceiveProps 和 ComponentWillUpdate 。
接下來 render 會被呼叫,比較的演算法會遞迴的處理先前和最新的結果。
Recursing On Children
預設下,對 DOM Node 的子元素做遞迴處理時, React 只是同時對兩個子元素的列表做迭代,當有不同時,就產生一個變話。
Example :在列表最後插入一個元素,因為先前的元素都符合,因此 React 在這邊可以運作得非常好;但在列表開始插入一個元素,則會獲得很差的效能,因為 React 會改變每一個元素,而非保留相同的元素
Key
為了解決這個問題, React 支援 key 的 attribute ,使用 key 來比對原始 tree 的子元素和新 tree 的子元素;在上述效能不好的例子中,加上 key 有助於轉換更有效率。
一般來說,找到 key 通常不難,通常列表中都含有獨特的 ID ;也可以給予適當的 ID 或是 hash 一部份的內容來產出 key ; key 只需要在兄弟姐妹中唯一,不需要全域中也是唯一。
作為最後手段,你可以傳入列表的索引值作為 key ,要列表不重新排列,這也可以運作得非常好,但重新排列會非常慢。當使用列表索引值作為 key 時,重新排列可能會造成 component state 的問題; component instance 會根據他們的 key 來重新使用或是更新,如果 key 是列表的索引值,搬移項目會改變索引值,結果會是:uncontrolled input 的 component state ,將會混在一起,或是不按照預期的方式更新。
Assumptions
- 演算法不會嘗試符合不同的 component 類型,如果你經常看到有非常相似的輸出,但是卻在兩種類型中互相交替,你可能會將它設成相同類型;在實踐中,尚未發現這可能是個問題。
- key 應該要是穩定的、可預測的和唯一的,不穩定的 key 將會造成許多 component instance 和 DOM node 重新創建,這個可能會造成效能下降,和遺失子 component 的 state 。
Portals
This includes event bubbling. An event fired from inside a portal will propagate to ancestors in the containing React tree, even if those elements are not ancestors in the DOM tree.
ReactDOM.createPortal(child, container)
使用 Portal 時,會將 child render 到 container 上
This includes event bubbling. An event fired from inside a portal will propagate to ancestors in the containing React tree, even if those elements are not ancestors in the DOM tree.
-
-
-