简体   繁体   中英

React strict mode and double rendering

Having such a simple CRA React app:

./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

I'm getting:

--> inside a Promise obj <--
--> Promise fulfilled <--
--> Promise fulfilled <--

on the console.

Why does the Promise fulfilled code is triggered 2 times? I know, that for React Strict mode the component is rendered twice but the example show some inconsistency here - the --> inside a Promise obj <-- message is called ONE time while the --> Promise fulfilled <-- TWICE? although both messages is being printed in the same function!?

According to the 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.

As a temporary workaround you can just do let log = console.log at the top level and then it'll always log.

Got this workaround from - https://github.com/facebook/react/issues/20090

Here is a code sandbox where you can see the expected output:-

编辑严格模式反应日志

The logging inside the then callback of the promise works because it's an async behavior outside the lifecycle methods of React. React doesn't silence those logs in Strict Mode . But the console.log("inside a Promise obj") is a synchronous task happening inside the Promise executor function which happens during the execution of your component's function body .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM