在 React useEffect 中使用 setInterval 函数时出现意外行为

问题描述 投票:0回答:1

当我在 useEffect 挂钩中将清理函数与 setInterval 结合使用时,我的 React 应用程序遇到了一种奇怪的行为。具体来说,当我隐藏清理函数时,计数总是“增加 2 而不是 1”。但是,当我添加清理函数时,计数会按预期增加 1。 这是代码片段:

import React, { useState, useEffect } from "react"; function Timer() { const [count, setCount] = useState(0); useEffect(() => { const id = setInterval(() => { setCount((prevCount) => prevCount + 1); }, 1000); // When the cleanup function below is uncommented, everything works as expected. // return () => { // clearInterval(id); // }; }, []); return ( <div className="Timer"> <h2>Timer Two</h2> <h3>{count}</h3> </div> ); } export default Timer;

我注意到从 
<React.StrictMode>

中删除

index.js
可以解决问题,而不需要清理功能。
任何人都可以解释为什么会发生这种行为吗? 

<React.StrictMode>

在这种情况下的作用是什么?如果您能提供任何见解或解决方案来帮助我理解和解决此问题,我将不胜感激。谢谢!

    

javascript reactjs asynchronous react-hooks settimeout
1个回答
0
投票

就像React中开发者的帮手。它使开发过程中的问题更加明显,但不会影响最终的应用程序。它可以帮助尽早发现并解决问题,从而使应用程序变得更好。

© www.soinside.com 2019 - 2024. All rights reserved.