const App = () => {
const [ counter, setCounter ] = useState(0)
console.log(counter)
return (
<>
<div>You clicked {counter} times.</div>
<button onClick={ () => setCounter(counter+1) }>Click me!</button>
</>
)
}
这是我的 react 组件。我的问题是当我运行它时,我在控制台中看到两次 0。然后当我点击按钮时,我在控制台中看到了两次 1。谁能解释为什么会这样?我原以为 0、1、2 在我单击按钮时只会在控制台中打印一次。
如果这个问题已经被回答或者我的问题标题与我的问题无关,请原谅,因为这是我在这里的第一个问题。
是因为React.StrictMode
如果你去你的 index.js ,你会发现你的 App
组件用 <React.StrictMode>
包裹.如果你去掉 StrictMode,你会注意到你的 App
组件将只渲染一次。
引用以下文档了解StrictMode
Strict mode can’t automatically detect side effects for you, but it
can help you spot them by making them a little more deterministic.
This is done by intentionally double-invoking the following functions:
Class component constructor, render, and shouldComponentUpdate methods
Class component static getDerivedStateFromProps method Function
component bodies State updater functions (the first argument to
setState) Functions passed to useState, useMemo, or useReducer
请引用:https://reactjs.org/docs/strict-mode.html