拥有如此简单的 CRA React
应用程序:
./index.tsx:
import React from 'react';
import ReactDOM from 'react-dom';
import Home from './components/Home';
ReactDOM.render(
<React.StrictMode>
<Home></Home>
</React.StrictMode>,
document.getElementById('root')
);
./components/Home.tsx:function Home() {
let myPromise = new Promise(function(myResolve, myReject) {
let x = 0;
console.log("--> inside a Promise obj <--");
if (x === 0) {
myResolve("OK");
} else {
myReject("Error");
}
});
myPromise.then(
function(value) {console.log("--> Promise fulfilled <--")},
);
return (
<div>
<b>Home Page</b>
</div>
)
}
export default Home
我越来越:--> inside a Promise obj <--
--> Promise fulfilled <--
--> Promise fulfilled <--
在控制台上。为什么 Promise 已完成的代码会被触发 2 次?我知道,对于 React Strict 模式,组件被渲染了两次,但示例在这里显示了一些不一致 -
--> inside a Promise obj <--
消息被调用一次,而 --> Promise fulfilled <--
两次!尽管两条消息都在同一个函数中打印!?
最佳答案
根据docs :-
Starting with React 17, React automatically modifies the console methods like console.log() to silence the logs in the second call to lifecycle functions. However, it may cause undesired behavior in certain cases where a workaround can be used.
作为临时解决方法,您可以执行
let log = console.log
在顶层,然后它将始终记录。从 - https://github.com/facebook/react/issues/20090 获得此解决方法
这是一个代码沙箱,您可以在其中看到预期的输出:-
记录 里面
then
promise 的回调有效,因为它是 之外的异步行为生命周期 react 的方法。 React 不会让那些 静音日志 在 严格模式 .但是
console.log("inside a Promise obj")
是 Promise
内部发生的同步任务在执行组件的 期间发生的 executor 函数函数体 .
关于javascript - React 严格模式和双重渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67019010/