useEffect 鉤子是 React 的基本組成部分,可讓您在功能元件中執行副作用。詳細分析如下:
useEffect(() => { // Your side effect code here return () => { // Cleanup code (optional) }; }, [dependencies]);
效果函數:第一個參數是包含副作用程式碼的函數。該函數將在渲染提交到螢幕後運行。
清理函數(可選):效果函數可以傳回一個清理函數,React 將在元件卸載時或效果再次運行之前呼叫函數。這對於清理訂閱或計時器很有用。
依賴關係數組:第二個參數是依賴關係數組。僅當依賴項之一發生變更時,該效果才會運作。如果傳遞空數組 ([]),則效果僅在初始渲染後執行一次(如 componentDidMount)。
import React, { useEffect, useState } from 'react'; const DataFetchingComponent = () => { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)) .catch(error => console.error('Error fetching data:', error)); }, []); // Runs only once after the initial render return{data ? JSON.stringify(data) : 'Loading...'}; };
import React, { useEffect } from 'react'; const EventListenerComponent = () => { useEffect(() => { const handleResize = () => { console.log('Window resized:', window.innerWidth); }; window.addEventListener('resize', handleResize); // Cleanup function to remove the event listener return () => { window.removeEventListener('resize', handleResize); }; }, []); // Runs only once after the initial render returnResize the window and check the console.; };
import React, { useEffect, useState } from 'react'; const TimerComponent = ({ delay }) => { const [count, setCount] = useState(0); useEffect(() => { const timer = setInterval(() => { setCount(prevCount => prevCount 1); }, delay); // Cleanup function to clear the timer return () => clearInterval(timer); }, [delay]); // Runs every time `delay` changes returnCount: {count}; };
useEffect hook 是一個強大的工具,用於處理功能元件中的副作用,這使得它對於現代 React 開發至關重要。透過了解其語法和最佳實踐,您可以有效地管理元件行為和副作用。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3