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