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: 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;
输出
示例 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;
输出
总结一下:
以上是了解 React 中的 useEffect() Hook的详细内容。更多信息请关注PHP中文网其他相关文章!