首页 >web前端 >js教程 >了解 React 中的 useEffect() Hook

了解 React 中的 useEffect() Hook

DDD
DDD原创
2024-10-05 12:17:021262浏览

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: margin: auto padding:>
      <h1 style="{{" textalign: marginbottom: color:>
        Users Data
      </h1>
      <h2 style="{{" textalign: marginbottom: color:>
        Understanding the useEffect() Hook in React By Sudhanshu Gaikwad
      </h2>

      {error ? (
        <p style="{{" color: textalign:>{error}</p>
      ) : (
        <table style="{{" width: bordercollapse: marginbottom:>
          <thead style="{{" backgroundcolor: color:>
            <tr>
              <th style="{{" padding: textalign:>ID</th>
              <th style="{{" padding: textalign:>Name</th>
              <th style="{{" padding: textalign:>Username</th>
              <th style="{{" padding: textalign:>Email</th>
            </tr>
          </thead>
          <tbody>
            {data.map((user) => (
              <tr key="{user.id}" style="{{" backgroundcolor: user.id : borderbottom: solid>
                <td style="{{" padding:>{user.id}</td>
                <td style="{{" padding:>{user.name}</td>
                <td style="{{" padding:>{user.username}</td>
                <td style="{{" padding:>{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: justifycontent: alignitems: height: backgroundcolor:>
      <div style="{{" backgroundcolor: borderradius: padding: boxshadow: rgba textalign:>
        <h1 style="{{" fontsize: fontfamily: sans-serif color: margin:>{count} seconds</h1>
        <p style="{{" margintop: fontsize: color:>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