首頁  >  文章  >  web前端  >  了解 React 中的 useEffect() Hook

了解 React 中的 useEffect() Hook

DDD
DDD原創
2024-10-05 12:17:02973瀏覽

React 在 16.8 版本中引入了 Hooks,最常用的 Hooks 之一是 useEffect()。 useEffect() Hook 讓我們在函數元件中執行副作用,例如取得資料、更新 DOM 或設定訂閱。

useEffect() 的工作原理
useEffect() Hook 接受兩個參數:

  1. 函數:這是將要運行的效果。此函數在元件渲染(或重新渲染)後執行。您可以將其視為“副作用”邏輯。
  2. 可選的依賴數組:這告訴 React 何時重新運行效果。如果您提供空數組 ([]),效果將僅在初始渲染後執行一次。

基本語法:


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;



輸出

Understanding the useEffect() Hook in React

範例 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;



輸出

Understanding the useEffect() Hook in React

總結一下:

  1. 使用 useEffect() 來執行諸如獲取資料、操作 DOM 或設定計時器等任務。
  2. 您可以透過傳遞依賴項陣列來控制效果何時運作。
  3. 在必要時始終透過從 useEffect() 回調傳回一個函數來清理效果。

以上是了解 React 中的 useEffect() Hook的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn