javascript - 这个 useState 钩子(Hook)在 React 中是如何工作的?

标签 javascript reactjs

<分区>

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

关于javascript - 这个 useState 钩子(Hook)在 React 中是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62898743/

相关文章:

javascript - ScrollTop 在 React Component 或检查器中不起作用

javascript - 渲染同一个 React 组件的多个,它可以渲染另一个组件的多个?

reactjs - React Router v4 从 MobX 存储操作导航?

javascript - jstree 验证节点的重命名,如果未验证,则回滚到旧名称

javascript - 如果当前页面需要 x 秒加载,重定向到另一个页面?

javascript - 使用mongodb在javascript中创建多个数组的一个数组

javascript - new Date ('yyyy-mm-dd' ) 将时区设置为本地时区,但 new Date ('yyyyy-mm-dd' ) 将时区设置为 GMT

reactjs - Nginx 404 静态文件( react 应用程序)

javascript - Vue有什么用,它使开发人员可以在DOM元素上使用class属性?

javascript - 如何连接到 mongodb 以及如何使用 node.js 程序从 mongodb 数据库打印所有集合的列表