reactjs - useState() 做双重渲染
问题描述
我在函数组件中使用 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'));
谢谢
解决方案
根据反应文档,如果您使用 StrictMode,这是一个有意的功能,可以帮助您检测意外的副作用
严格模式不能自动为您检测副作用,但它可以通过使它们更具确定性来帮助您发现它们。这是通过有意双重调用以下函数来完成的:
- 类组件构造函数、render 和 shouldComponentUpdate 方法
- 类组件静态 getDerivedStateFromProps 方法
- 功能组件体
- 状态更新函数(setState 的第一个参数)
- 传递给 useState、useMemo 或 useReducer 的函数
注意:这只适用于开发模式。在生产模式下不会重复调用生命周期。
https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects
推荐阅读
- javascript - Onclick 事件处理程序给出一个值 [JS]
- python - 如何在不刷新页面python烧瓶的情况下自动更新数据?
- deployment - 如何优化 Tableau 仪表板的部署策略?
- reporting-services - SSRS 和顽固的 Excel 序列号
- html - powerapp 添加不断变化的超链接
- wordpress - 我无法在实时服务器上上传我的本地主机网站。它没有显示背景图像
- c# - Entity Framework Core:读取和删除数据之间的事务
- apache-spark - Spark-kafka:从 Spark 写入流时出现 org.apache.kafka.common.errors.TimeoutException
- angular - 限制刷新页面|浏览器限制| 角 6 |
- javascript - 函数内的变量范围