gpt4 book ai didi

reactjs - useState() 进行双重渲染

转载 作者:行者123 更新时间:2023-12-03 13:45:08 25 4
gpt4 key购买 nike

我在函数组件中使用 useState() ,并且第一次渲染调用了两次。这是正确还是错误?如果正确的话为什么会渲染两次? setCount 也会渲染组件两次。

function Example() {
const [count, setCount] = useState(0);
console.log("render");

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

ReactDOM.render(<Example />, document.getElementById('uu5'));

谢谢

最佳答案

根据 React 文档,这是一个有意的功能,可以帮助您在使用 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

Note: This only applies to development mode. Lifecycles will not be double-invoked in production mode.

https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects

关于reactjs - useState() 进行双重渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54927622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com