这是我为一个页面编写的React代码:
function ExportViewerPage(): JSX.Element {
const [hasPrinted, setHasPrinted] = useState(false);
if (!hasPrinted) {
setHasPrinted(true);
console.log("Inside if loop, hasPrinted: ", hasPrinted)
setTimeout(() => {
console.log("Executing setTimeout: ", hasPrinted)
});
}
return (<div>Page</div>)
}
export default ExportViewerPage;
最终,代码应该只执行一次 setTimeout
函数中的代码。然而,控制台中实际上会看到它执行了两次:
Inside if loop, hasPrinted: false
Executing setTimeout: false
Executing setTimeout: false
奇怪的是,在
setTimeout
函数之前立即记录的控制台日志只执行一次,因此setTimeout
没有被调用两次,并且hasPrinted
被正确设置。这在Chrome和Firefox上都会发生。我注意到,如果我在
next.config.js
文件中关闭reactStrictMode
,setTimeout
将只触发一次。但我仍然困惑于为什么在打开reactStrictMode
的情况下setTimeout
会触发两次,但是它上方的控制台日志只记录一次。