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