javascript - React 严格模式和双重渲染

标签 javascript reactjs promise

拥有如此简单的 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 获得此解决方法
这是一个代码沙箱,您可以在其中看到预期的输出:-
Edit strict-mode-react logging
记录 里面then promise 的回调有效,因为它是 之外的异步行为生命周期 react 的方法。 React 不会让那些 静音日志 严格模式 .
但是 console.log("inside a Promise obj")Promise 内部发生的同步任务在执行组件的 期间发生的 executor 函数函数体 .

关于javascript - React 严格模式和双重渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67019010/

相关文章:

javascript - IBM Watson Visual Recognition - 由于凭证无效,访问被拒绝

javascript - 在 React Native 中导出方法/函数

css - body 元素没有边距,但子元素的边距会影响 body 的边距

javascript - Redux-Form 理解多页表单 Ajax PUT

typescript - 手动创建 Promise 和使用 async/await API 之间有实际区别吗?

javascript - 在 Mongoose 模式默认日期值中将月份添加到当前日期

javascript - JSON Encode 转换为 null - 太奇怪了

javascript - Polymer 添加具有属性的 Html 标签

javascript - 如何等待少数 HTTP promise 完成并仅在所有 promise 都失败时才显示模式

javascript - Node.js 中的对象字面量会阻塞吗