【发布时间】:2021-04-22 05:48:03
【问题描述】:
考虑以下代码:
import React from "react";
function App() {
console.log("render");
setTimeout(() => {
console.log("time is up");
}, 2000);
return <div>nothing to see here</div>;
}
export default App;
我预期以下输出:
render
time is up
但 Chrome 控制台中的真实输出是:
注意time is up之前的2,这表明time is up被输出了两次。
我不明白为什么 time is up 会输出两次。谁能解释一下?
【问题讨论】:
-
什么是
timers?这只是对全局setTimeout的导入还是其他什么? -
@jonrsharpe Visual Studio Code 为我做了这些。我删除了它,但观察到相同的行为。
-
当我在本地运行时,我看到
render和time is up两次,无法重现。 -
@stefan.at.wpf 您能否从您的 index.js 中验证您没有在 React.StrictMode 中运行?
-
@PrashantVishwakarma 我在严格模式下运行,在移除严格模式后,time is up 只按预期显示一次。我不明白为什么严格模式会改变这一点。你能解释/发布作为答案吗?
标签: javascript reactjs create-react-app