react中useEffect Hook作用小結(jié)
`useEffect`是一個(gè)用于處理副作用(Side Effects)的 Hook
一、處理副作用
1. 副作用的概念
副作用是指在組件渲染過程中執(zhí)行的、會(huì)影響組件外部環(huán)境或具有外部可見影響的操作。
常見的副作用包括數(shù)據(jù)獲?。ㄈ鐝姆?wù)器獲取數(shù)據(jù))、訂閱外部數(shù)據(jù)源(如消息隊(duì)列、事件總線)、手動(dòng)操作 DOM(如修改頁面標(biāo)題、滾動(dòng)位置)以及設(shè)置定時(shí)器等。
2. useEffect 基本用法
2.1 語法結(jié)構(gòu)
`useEffect`接受兩個(gè)參數(shù),第一個(gè)參數(shù)是一個(gè)函數(shù),稱為副作用函數(shù)(Effect Function),在這個(gè)函數(shù)內(nèi)部執(zhí)行實(shí)際的副作用操作。第二個(gè)參數(shù)是一個(gè)可選的依賴項(xiàng)數(shù)組(Dependency Array)。
import React, { useEffect, useState } from "react"; const MyComponent = () => { const [count, setCount] = useState(0); useEffect(() => { // 這是一個(gè)副作用函數(shù),這里模擬從服務(wù)器獲取數(shù)據(jù) console.log("Fetching data..."); return () => { // 可選的清理函數(shù),用于在組件卸載或依賴項(xiàng)變化時(shí)清理副作用 console.log("Cleaning up..."); }; }, []); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }; export default MyComponent;
在這個(gè)例子中,副作用函數(shù)在組件掛載時(shí)執(zhí)行,因?yàn)橐蕾図?xiàng)數(shù)組為空(`[]`),表示這個(gè)副作用只在組件初始化時(shí)觸發(fā)一次。副作用函數(shù)還返回了一個(gè)清理函數(shù),用于在組件卸載或依賴項(xiàng)變化時(shí)執(zhí)行清理操作。
二、模擬生命周期方法
1. 替代 componentDidMount
在類組件中,`componentDidMount`方法在組件掛載到 DOM 后立即執(zhí)行。在函數(shù)組件中,可以使用`useEffect`來實(shí)現(xiàn)類似的功能。當(dāng)`useEffect`的依賴項(xiàng)數(shù)組為空時(shí),副作用函數(shù)在組件第一次渲染(掛載)后執(zhí)行,相當(dāng)于`componentDidMount`。
import React, { useEffect, useState } from "react"; const MyComponent = () => { const [data, setData] = useState(null); useEffect(() => { // 模擬在組件掛載后獲取數(shù)據(jù),相當(dāng)于componentDidMount fetch("https://example.com/api/data") .then((response) => response.json()) .then((jsonData) => setData(jsonData)); }, []); return <div>{data ? <p>{data}</p> : <p>Loading...</p>}</div>; }; export default MyComponent;
2. 替代 componentDidUpdate
在類組件中,`componentDidUpdate`方法在組件每次更新(`state`或`props`變化)后執(zhí)行。在函數(shù)組件中,可以通過在`useEffect`的依賴項(xiàng)數(shù)組中指定依賴項(xiàng)來模擬`componentDidUpdate`。當(dāng)依賴項(xiàng)發(fā)生變化時(shí),副作用函數(shù)會(huì)重新執(zhí)行,類似于`componentDidUpdate`。
import React, { useEffect, useState } from "react"; const MyComponent = () => { const [count, setCount] = useState(0); const [data, setData] = useState(null); useEffect(() => { // 當(dāng)count變化時(shí),重新獲取數(shù)據(jù),類似于componentDidUpdate if (count > 0) { fetch("https://example.com/api/data") .then((response) => response.json()) .then((jsonData) => setData(jsonData)); } }, [count]); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> {data ? <p>{data}</p> : <p>Loading...</p>} </div> ); }; export default MyComponent;
3. 替代 componentWillUnmount
在類組件中,`componentWillUnmount`方法在組件卸載前執(zhí)行,用于清理資源。在函數(shù)組件中,`useEffect`的副作用函數(shù)返回的清理函數(shù)在組件卸載或依賴項(xiàng)變化時(shí)執(zhí)行,從而替代了`componentWillUnmount`的功能。
import React, { useEffect, useState } from "react"; const MyComponent = () => { const [count, setCount] = useState(0); useEffect(() => { const timer = setInterval(() => { setCount(count + 1); }, 1000); return () => { // 組件卸載或依賴項(xiàng)變化時(shí)清除定時(shí)器,相當(dāng)于componentWillUnmount clearInterval(timer); }; }, []); return ( <div> <p>Count: {count}</p> </div> ); }; export default MyComponent;
三、依賴項(xiàng)管理和優(yōu)化
1. 依賴項(xiàng)的作用
1.1 決定副作用執(zhí)行時(shí)機(jī)
例如:如果一個(gè)副作用函數(shù)依賴于組件的某個(gè)狀態(tài)值,將這個(gè)狀態(tài)值放入依賴項(xiàng)數(shù)組中,那么當(dāng)這個(gè)狀態(tài)值改變時(shí),副作用函數(shù)就會(huì)重新運(yùn)行。這樣可以確保副作用與組件的狀態(tài)和屬性保持同步。
2. 優(yōu)化性能
例如:在不必要的時(shí)候重復(fù)獲取數(shù)據(jù)或重新訂閱事件,浪費(fèi)資源并可能導(dǎo)致應(yīng)用程序性能下降。
3. 優(yōu)化策略和常見錯(cuò)誤
3.1 空依賴項(xiàng)數(shù)組的優(yōu)化與風(fēng)險(xiǎn)
例如:初始化數(shù)據(jù)獲取或設(shè)置全局事件監(jiān)聽器。但如果在副作用函數(shù)中使用了組件的狀態(tài)或?qū)傩?,并且沒有將它們包含在依賴項(xiàng)數(shù)組中,就會(huì)導(dǎo)致閉包問題。
import React, { useEffect, useState } from "react"; const MyComponent = () => { const [count, setCount] = useState(0); useEffect(() => { // 錯(cuò)誤:沒有將count包含在依賴項(xiàng)數(shù)組中,導(dǎo)致閉包問題 console.log("Count:", count); }, []); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }; export default MyComponent;
3.2 正確指定依賴項(xiàng)
為了避免上述問題,需要將副作用函數(shù)中使用的所有組件的狀態(tài)、屬性以及其他外部函數(shù)(如果在副作用函數(shù)內(nèi)部調(diào)用)都包含在依賴項(xiàng)數(shù)組中。
import React, { useEffect, useState } from "react"; const MyComponent = () => { const [count, setCount] = useState(0); useEffect(() => { console.log("Count:", count); }, [count]); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }; export default MyComponent;
到此這篇關(guān)于react中useEffect Hook作用小結(jié)的文章就介紹到這了,更多相關(guān)react useEffect Hook內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React自定義hooks同步獲取useState的最新狀態(tài)值方式
這篇文章主要介紹了React自定義hooks同步獲取useState的最新狀態(tài)值方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03React函數(shù)式組件Hook中的useState函數(shù)的詳細(xì)解析
Hook 就是 JavaScript 函數(shù),這個(gè)函數(shù)可以幫助你鉤入(hook into) React State以及生命周期等特性,這篇文章主要介紹了React Hook useState函數(shù)的詳細(xì)解析的相關(guān)資料,需要的朋友可以參考下2022-10-10