每日進度0 Flashcards
what are the phases in react life cycle?
- Render Phase
2. Commit Phase
what are the life cycle methods in [the render phase] ?
- constructor
- render
// 絕對!!不能在這兩個methods裡面做side effect action 或 this.setState
what are the life cycle methods in [the commit phase] ?
- React更新 DOM 和 refs [!!!]
- componentDidMount (Mounting)
- componentDidUpdate (Updating)
- componentWillUnmount (Unmounting)
在constructor中建議不要做的 3 件事情
- this.setState (因為constructor是在 Render Phase)
- ajax
- (建議不要而已,除非你很確定指定初值只做一次對你來說是OK的,那就完全可以用!) 用prop來指定state的初值
render中不要做的 2 件事情
- this.setState (因為render是在 Render Phase)
- ajax
// 跟constructor中不能做的3件事情差不多,除了第三件事情
React16之後,可以回傳哪一種 “容器”
React16之後,可以回傳一個陣列,並將多個components放置其中回傳,而不再需要用個外層元素包裝多個components
既然React16之後可以直接回傳 “容器”,那為什麼有的地方還是要用React16之前的 “外層元素包裝多個元素”
很多個lib.還是align舊的標準,例如: React Router
[i.e.] (不) 合法
<h1>標題</h1>
<span>lorem..</span>
[i.e.] 合法 (React 16之 “前” )
<div>
<h1>標題</h1>
<span>lorem..</span>
</div>
[i.e.] (不) 合法 only in React Router
<div> [ <h1>標題</h1>, <span>lorem..</span>, ] </div>
[i.e.] 合法 (React 16之 “後”: Fragment)
<h1>標題</h1> <span>lorem..</span>
React16之後的 “虛擬元素”
Fragment
Context API
用來打破Component Level,有了Context API其實就不太需要再另外使用Redux一類的State Lib.
Portal
傳送門,使能打破Component Level,將必要的Component渲染在Wrapper以外的其他層級 (i.e. 與Wrapper平級或其他)
Hooks
使能用Functional Component的方式去實作以往需要用Classical的方式撰寫的Component
`
back tick
如何拆分Components
- easy to test
2. 只負責單一任務 each component with its concern
state
batches work (schedule it), let React handle it so that we don’t have to worry for our components
API call in async/await way
const response = await fetch(API); const ajaxData = await response.json(); const { results = [] } = ajaxData; const [resultObject = {}] = results;
about useEffect
// useEffect 用在處理副作用 // useEffect必須傳入 "函式" 來做使用 // 可以用來取代傳統的生命週期函式 (相較於以往使用生命週期函式,使用useEffect可以避免同類邏輯的分散) // useEffect會保證在每次 "render完成" 之後再執行 // 執行順序 // 1. 先判斷第二個參數的陣列中,值的內容是否 "不同",不同才會繼續做下去 // 2. 執行上次存下來的clean up function // 3. 執行useEffect的內容 // 4. 暫存 useEffect return 的 clean up function,待下次useEffect執行時使用
// 如果不傳入第二個參數,則有可能不斷的移除監聽、加入監聽 /* // Mount with { friend: { id: 100 } } props ChatAPI.subscribeToFriendStatus(100, handleStatusChange); // 執行第一個 effect
// Update with { friend: { id: 200 } } props ChatAPI.unsubscribeFromFriendStatus(100, handleStatusChange); // 清除前一個 effect ChatAPI.subscribeToFriendStatus(200, handleStatusChange); // 執行下一個 effect // Update with { friend: { id: 300 } } props ChatAPI.unsubscribeFromFriendStatus(200, handleStatusChange); // 清除前一個 effect ChatAPI.subscribeToFriendStatus(300, handleStatusChange); // 執行下一個 effect
// Unmount ChatAPI.unsubscribeFromFriendStatus(300, handleStatusChange); // 清除最後一個 effect */
// 傳入空陣列 => componentDidMount (, componentWillUnmount) // 什麼都不傳入 => componentDidUpdate