为什么我的简单反应组件打印控制台两次? [英] Why my simple react component print console twice?
问题描述
我制作了一个简单的组件,当点击按钮时,数字状态a"会增加.
并且我在组件内部编写了 console.log()
来检查它何时呈现.我希望 console.log
在单击按钮时执行一次,因为组件的状态已更改.
但是,我错了,console.log()
被执行了两次.
有什么问题吗?还是正确的?我错过了什么?
这是我的代码
A.jsx
import React, {useState} from 'react';const A = () =>{const [a, setA] = useState(0);const onClick = () =>setA(a + 1);console.log('渲染')返回 (<div><p>a:{a}</p><button onClick = {onClick}>button</button>
)}出口默认A;
index.jsx
从'react'导入React;从 'react-dom' 导入 ReactDOM;从'./App'导入应用程序;从'./components/A'导入A;import * as serviceWorker from './serviceWorker';ReactDOM.render(<React.StrictMode><A/></React.StrictMode>,document.getElementById('root'));serviceWorker.unregister();
此应用由 CRA 使用 typescript 创建.仅此而已.
谢谢.
****PLUS******
我检查了 React 开发工具 Profiler 以检查在单击按钮并更改状态时组件是否真的渲染了两次.它在下面显示了我的结果
我认为只有一个渲染.如果组件真的渲染了一次,为什么 console.log 会执行两次?
我认为这是因为 React.StrictMode
这只发生在开发中.如果你删除 React.StrictMode
你只会得到 1 个日志.
有关更多详细信息,请查看 react repo 上的此线程:
https://github.com/facebook/react/issues/15074
在进一步阅读时,我也在 React 文档中发现了这一点:https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects
希望这会有所帮助!
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?
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!
这篇关于为什么我的简单反应组件打印控制台两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!