简体   繁体   English

React 组件渲染两次,不使用状态钩子的函数组件只渲染一次

[英]React components are rendered twice, function components that don't use state hooks are rendered only once

Demo code's codesandbox url: https://codesandbox.io/s/hungry-goldstine-gmvz4演示代码的codesandbox url: https ://codesandbox.io/s/hungry-goldstine-gmvz4

Class component is rendered twice, without Props and State;类组件渲染两次,没有 Props 和 State; Function components that do not use useState hook are rendered only once and using useState hook will render twice.不使用useState钩子的函数组件useState渲染一次,而使用useState钩子会渲染两次。

Is it rendered twice for get State and Props values?是否为 get State 和 Props 值渲染了两次?

A class component is a stateful component whether or not the state is initialized?类组件是有状态组件,无论状态是否已初始化?

Can anyone help me understand this question?谁能帮我理解这个问题? Thank you!!!谢谢!!!

additional a image:补充一张图片: 在此处输入图片说明

As comment @Sagar More, StricktMode cause it.正如评论@Sagar More, StricktMode导致的。

Output without StrickMode没有StrickMode输出在此处输入图片说明

See docs查看文档

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 methods:这是通过有意重复调用以下方法来完成的:

Class component constructor method类组件构造方法

The render method渲染方法

setState updater functions (the first argument) setState 更新器函数(第一个参数)

The static getDerivedStateFromProps lifecycle静态 getDerivedStateFromProps 生命周期

The shouldComponentUpdate method shouldComponentUpdate 方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM