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
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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…