# [Udemy - React] 課程流程筆記(sec. 14) ###### tags: `Udemy 課程筆記` `React` `前端筆記` 記錄每個章節在幹嘛,之後看完影片動手實作的時候可以回來看流程: ## Sec. 14 ### 177 打 API - 使用 `fetch` + `promise` 打 API - 先暫時透過 `onClick` 觸發執行打 API - 不要直接用 API 的資料格式建立 component props,而是先找需要什麼 properties,然後再開一個屬於該 component props ### 178. `fetch` 搭配 `async / await` 讓程式碼看起來就像「同步」一樣 ### 179. 新增 isLoaidng state - 開新的 `state`(`isLoading`),以便更新 UI - 多判斷是否有 loading 及 是否是沒有 movies > ~~在 `async` 函式內下 `console.log()` 觀察 component re-running 時 `async` 函式是否再次執行?~~ ~~但照理說應該會,因為 re-running 是重新執行 function body 內的函式碼,以這個思維推的話 `async` 函式似乎會被重新叫用 (但這樣子不久代表重新呼叫 API 嗎?)~~ 幹,被誤導了,這個函式是 event 的 callback,所以只會建立新的 scope,不是會叫用啦! ### 180. 顯示 error message - 開新的 `state`(`error`)處理錯誤訊息 - 因為 `fetch` 只會在網路有問題的時候才會 reject the promise,因此需要自己用其他屬性判斷是否是錯誤(比如 `response.ok` 或者 `response.state`) - 先接 default 的錯誤訊息,之後再接客製化的錯誤訊息:`Something went wrong.` - 避免 view 的部分放太多邏輯,多開一個變數 `content` 依照當前 state 顯示不同的內容後再把判斷的結果丟到 view -> 也可以包成一個函式! ### 181. 使用 `useEffect` 達成初次 render component 就打 API - `useEffect` 會在每次 component render 後執行 -> 透過這個特性實作初次 render 後打 API - `useEffect` 藉由 dependency array 決定要不要重新叫用 `useEffect` 內的函式 - ==The best practice: You should list all dependencies you use inside of the effect function in the dependencies array== - `useEffect` + `useCallback` 的搭配,確保不會因為 component 的 re-render 重複呼叫 API,造成無限迴圈 - 之後要理解 `useEffect` 的觀念(關鍵字:`side effect`、`external state`) ### 182. 因為要發送 `POST` 請求,因此使用 firebase 模擬 database - firebase -> realtime database - 用新的 repo -> 06-preparing-the-project-for-the-next-steps(裡面多了 `AddMovie.js` 處理 create) ### 183. 實作 `POST` request - firebase: firebaseURL/nodeName.json - 因為 firebase 會自動生成亂數,且會得到這樣子的資料結構(`id: { dataObj }`),因次除了課程中多開資料 + 執行迴圈使用 `push`,也可以用 `Object.entries() + map()` 更快速地拿到我想要的資料結構 - 實作 delete 已經 updata(提示,皆用 firebase 提供的 `id`,當作找尋目標的手段) - 切記非同步都要處理錯誤
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up