ReactJS使用useTimeout自定义钩子
在使用React构建应用程序时,我们经常会遇到超时的情况。setTimeout()函数在指定的时间段之后执行代码。通常情况下,当使用setTimeout时,我们不需要担心清除超时。然而,在React中使用setTimeout方法可能会有一些挑战,因为我们可能希望在一定时间后操作数据。
即使组件可能在此之前已被删除,超时仍然试图启动。这甚至可能导致内存泄漏。为了解决这个问题,我们必须跟踪我们在代码中创建的超时并清除它们。这样可以工作,但是当卸载时记得清理它可能会很麻烦。因此,我们将使用自定义的setTimeout钩子。
useTimeout钩子以声明的方式实现了setTimeout方法。 它遵循与自定义useInterval钩子类似的原则。
在使用上,useTimeout与setTimeout方法非常类似:
语法:
useTimeout(() => {
// func
}, delay);
useTimeout Hook接受一个函数和一个延迟,其中,
- func: 它是在延迟之后重复执行的函数。
- delay: 它指示在执行函数之前等待多长时间。
让我们来看一下在React中如何使用useTimeout自定义hook的示例:
方法: 我们将使用自定义useTimeout hook在指定的时间后显示一条消息。
按照以下步骤开始:
步骤1: 创建一个项目目录,切换到终端,并使用以下命令创建一个名为message的react应用程序:
npx create-react-app message
创建消息应用程序后,通过键入以下命令切换到新的消息文件夹:
cd message
步骤2: 修改您的项目结构。在src文件夹中添加一个 useTimeout.js 文件。我们将修改文件夹并保留我们在此示例中所需的文件。现在,请确保您的文件结构看起来像这样:
步骤3: 将以下代码包含在您的 index.html 文件中,该文件位于项目目录的public文件夹中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1" />
<meta name="theme-color"
content="#000000" />
<meta name="description"
content="Web site created using create-react-app" />
<title>Message App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
步骤4: 创建useTimeout自定义钩子。
在 useTimeout.js 文件中,我们将编写一个函数来创建一个自定义的useTimeout钩子,我们可以在我们的消息应用程序中使用它。
- useTimeout函数接受一个回调函数和一个延迟作为参数。
- 我们将使用 useRef() 钩子来为回调函数创建一个引用。
- 我们将使用 useEffect 钩子来跟踪最新的回调函数并清除超时。
- useEffect钩子清理上一个效果,但是如果不重置时间,setTimeout方法仍然引用旧状态。因此,我们创建了一个mutable变量savedCallback来跟踪先前的回调函数。
- 我们将保存的回调函数保存为savedCallback.current。
useTimeout.js:
import React, { useState, useEffect, useRef } from 'react';
// creating the custom useTimeout hook
const useTimeout = (callback, delay) => {
// Creating a ref
const savedCallback = useRef();
// To remember the latest callback .
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Setting and clearing up a timeout
useEffect(() => {
const func = () => {
savedCallback.current();
}
if (delay !== null) {
let id = setTimeout(func, delay);
return () => clearTimeout(id);
}
}, [delay]);
};
export default useTimeout;
** 步骤5:** 创建消息组件。
- 我们将使用useState和useTimeout自定义hooks。
- 我们将在5秒后显示消息。
- 我们将在自定义的useTimeout hook中传递逻辑和延迟参数。
App.js:
import { React, useState } from 'react';
import './App.css';
import useTimeout from './useTimeout';
const App = () => {
const [text, setText] = useState(false);
//using the custom useTimeout hook
useTimeout(() => {
setText(true);
}, 5000);
return (
<div className='msg'>
<h1>
{text
? 'Hey Geek, welcome back to geeksforgeeks.'
: 'Your message is loading......'}
</h1>
</div>
)
}
export default App;
步骤6: 将以下代码添加到 App.css 以为消息应用程序添加样式。
App.css:
.msg {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
border: 4px solid darkGreen;
margin: 2rem;
}
步骤7: 将下面的代码添加到 index.js 文件中。index.js文件作为主入口点,在其中,App.js文件在DOM的根ID处被渲染。
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
运行应用的步骤: 使用以下命令运行应用:
npm start
输出: 默认情况下,React项目将在3000端口运行。您可以在浏览器上通过localhost:3000访问它。
五秒钟后,消息将出现。