Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
860 views
in Technique[技术] by (71.8m points)

reactjs - Why my simple react component print console twice?

I made a simple components that number state 'a' is increased when the button is clicked.

and I wrote console.log() inside component to check when it is rendered. I expected the console.log is executed once when the button is clicked because component's state is changed.

But, I was wrong and console.log() is executed twice.

Is something wrong? or Is it correct? What i missed?

here is my code

A.jsx

import React, {useState} from 'react';

const A = () => {
    const [a, setA] = useState(0);
    const onClick = () => setA(a + 1);
    console.log('render')

    return (
        <div>
            <p>a : { a}</p>
            <button onClick = {onClick}>button</button>
        </div>
    )
}

export default A;

index.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import A from './components/A';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <A />
  </React.StrictMode>,
  document.getElementById('root')
);

serviceWorker.unregister();

This app is created by CRA with typescript . That's all.

Thanks.

****PLUS******

I checked React dev tools Profiler to check the component is really rendered twice when a button is clicked and state is changed. It show me result below

enter image description here

I think there was only one render. If the component was really rendered once, why the console.log exected twice?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think this is because of React.StrictMode this only happens in development. If you remove React.StrictMode you will get only 1 log.

For more details, check this thread on react repo:

https://github.com/facebook/react/issues/15074

On reading further I found this on React docs as well: https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects

Hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...