【问题标题】:Why useState makes the component to render twice?为什么 useState 让组件渲染两次?
【发布时间】:2020-07-11 00:43:36
【问题描述】:

也许你们中的一些人可以睁开我的眼睛。

我不明白为什么在这段代码中:https://codesandbox.io/s/use-state-renders-twice-6r1xl 组件App在挂载并点击按钮时渲染两次(console.log被调用两次)

代码:

export default function App() {
  const [clicked, setClicked] = React.useState(false);
  const handleClick = () => setClicked(!clicked);
  console.log(clicked);
  return <button onClick={handleClick}>click</button>;
}

结果:

false
false
true
true

它只是一个钩子useState的功能组件!

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

这是因为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

在此处检查没有 StrictMode 的应用:https://codesandbox.io/s/use-state-renders-twice-3vroc

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2020-09-28
    • 2020-03-17
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    相关资源
    最近更新 更多