### 參閱教學: 1. [What is the 'window' Object (JavaScript)](https://youtu.be/c5KEnb6vyjs?si=Edmlot1eE5zF5A9Y) 2. [一定是大概看看的 Mdn](https://developer.mozilla.org/en-US/docs/Web/API/Window) - 在 JavaScript 中,window 是全局對象(global object) ```js console.log(window); // or 直接在瀏覽器的 console 輸入: window ``` - 展開就可以得到很多「屬性」。 - 例如早期的 var 宣告方式,就是 window 底下的全域對象。 ```js var a = 1; console.log(window.a); // 1 ``` - 但是用 ES6 的 let 宣告變數,就不屬於全域變數了,它有所謂的作用域性質: - let、const ```js let b = 2; console.log(window.b); // undefined ``` ### 自身的使用經驗: - [練習專案](https://youtu.be/CHGHuF24Cjw),裡頭的 **Cursor components** ```jsx import { useEffect, useState } from "react"; import "./cursor.scss"; import { motion } from "framer-motion"; const Cursor = () => { // 使用了 State 定義了物件初始 x,y const [position, setPosition] = useState({ x: 0, y: 0 }); useEffect(() => { // 每次 re-render 之後,去載入這段函數,改變 State const mouseMove = (e) => { setPosition({ x: e.clientX, y: e.clientY }); }; window.addEventListener("mousemove", mouseMove); // 清理函數,會在下一次執行 useEffect 時,先清除 return () => { window.removeEventListener("mousemove", mouseMove); }; }, []); return ( <motion.div className="cursor" animate={{ x: position.x + 10, y: position.y + 10 }} ></motion.div> ); }; export default Cursor; ``` ### 順便複習一下吧,useEffect 及其 render 的流程 - 使用者打開網頁: 當使用者首次打開網頁,React 開始進行組件的掛載階段。 初次渲染(Mounting): useEffect 的效果會在組件初次渲染完成後執行。 清理函數(如果存在)將在下一次 useEffect 執行之前執行。 - 更新階段(可能重複多次): 如果有依賴於 state 或 props 的 useEffect,當這些依賴發生變化時,先前的 useEffect 效果將以清理函數結束。 新的 useEffect 效果會在清理函數之後執行,確保任何必要的清理在新的效果之前完成。 - 卸載階段: 如果組件即將卸載,清理函數將在卸載之前執行。 簡而言之,整個流程可以描述為: ``` 使用者打開網頁 -> 初次渲染(Mounting)-> 更新階段(可能重複多次) -> 卸載階段 ``` - 在每個 useEffect 的執行中,都包括了清理函數的執行,確保在下一次效果開始之前進行必要的清理。 ### 為何我們需要清理函數? - 一方面避免 memory-leak - 二來是,白話說,不需要的佔據就把它清除掉,不然會佔據記憶體空間,這很影響效能。
×
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