React 在 16.8 版本中引入了 Hooks,最常用的 Hooks 之一是 useEffect()。 useEffect() Hook 讓我們在函數元件中執行副作用,例如取得資料、更新 DOM 或設定訂閱。
useEffect() 的工作原理
useEffect() Hook 接受兩個參數:
基本語法:
useEffect(() => { // Your side effect code here }, [dependencies]);
範例1:取得資料
import React, { useEffect, useState } from "react"; function DataFetchingComponent() { const [data, setData] = useState([]); const [error, setError] = useState(null); useEffect(() => { // Fetch data from an API fetch("https://jsonplaceholder.typicode.com/users") .then((response) => response.json()) .then((json) => setData(json)) .catch((err) => setError("Error fetching data")); }, []); return ( <div style={{ maxWidth: "1200px", margin: "0 auto", padding: "20px" }}> <h1 style={{ textAlign: "center", marginBottom: "20px", color: "#333" }}> Users Data </h1> <h2 style={{ textAlign: "center", marginBottom: "20px", color: "#333" }}> Understanding the useEffect() Hook in React By Sudhanshu Gaikwad </h2> {error ? ( <p style={{ color: "red", textAlign: "center" }}>{error}</p> ) : ( <table style={{ width: "100%", borderCollapse: "collapse", marginBottom: "20px", }} > <thead style={{ backgroundColor: "black", color: "white" }}> <tr> <th style={{ padding: "10px", textAlign: "left" }}>ID</th> <th style={{ padding: "10px", textAlign: "left" }}>Name</th> <th style={{ padding: "10px", textAlign: "left" }}>Username</th> <th style={{ padding: "10px", textAlign: "left" }}>Email</th> </tr> </thead> <tbody> {data.map((user) => ( <tr key={user.id} style={{ backgroundColor: user.id % 2 === 0 ? "#f2f2f2" : "white", borderBottom: "1px solid #ddd", }} > <td style={{ padding: "10px" }}>{user.id}</td> <td style={{ padding: "10px" }}>{user.name}</td> <td style={{ padding: "10px" }}>{user.username}</td> <td style={{ padding: "10px" }}>{user.email}</td> </tr> ))} </tbody> </table> )} </div> ); } export default DataFetchingComponent;
輸出
範例 2:設定計時器
import React, { useState, useEffect } from "react"; function TimerComponent() { const [count, setCount] = useState(0); useEffect(() => { const interval = setInterval(() => { setCount((prevCount) => prevCount + 1); }, 1000); return () => clearInterval(interval); }, []); return ( <div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "100vh", backgroundColor: "#f0f4f8" }}> <div style={{ backgroundColor: "#fff", borderRadius: "10px", padding: "30px 50px", boxShadow: "0 4px 8px rgba(0, 0, 0, 0.1)", textAlign: "center" }}> <h1 style={{ fontSize: "3rem", fontFamily: "Roboto, sans-serif", color: "#333", margin: "0" }}>{count} seconds</h1> <p style={{ marginTop: "15px", fontSize: "1.2rem", color: "#666" }}>Timer running with useEffect hook</p> </div> </div> ); } export default TimerComponent;
輸出
總結一下:
以上是了解 React 中的 useEffect() Hook的詳細內容。更多資訊請關注PHP中文網其他相關文章!