由于严格的模式,我的反应组件呈现两次
我的反应组件渲染两次。因此,我决定进行逐条调试,问题在这里:
if ( workInProgress.mode & StrictMode) {
instance.render();
}
react-dom.development.js
是因为严格的模式吗?我可以禁用吗?什么是严格模式?我需要吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
strictmode渲染组件两次(在开发但不生产上)以检测您的代码问题并警告您(这很有用)。
如果您在应用程序中启用了strictmode,但不记得启用它,则可能是因为您最初使用Create-React-app应用程序或类似于创建您的应用程序,该应用程序最初可以自动启用StrictMode。
例如,您可能会发现您的{app}由
< react.strictmode>
在您的index.js中包裹:如果是这样,则可以通过删除
< react react来禁用strictmode。 strictmode>
标签:StrictMode renders components twice (on dev but not production) in order to detect any problems with your code and warn you about them (which can be quite useful).
If you have StrictMode enabled in your app but don't remember enabling it, it might be because you used create-react-app or similar to create your app initially, which automatically enables StrictMode by default.
For example, you might find that your {app} is wrapped by
<React.StrictMode>
in your index.js:If so, you can disable StrictMode by removing the
<React.StrictMode>
tag:是的,您必须删除严格的模式
来源: react docs:react docs:严格模式
Yes you have to remove Strict mode as
Source: React Docs: Strict Mode
对于Next.js用户,像my-felp,
默认情况下还启用了严格的模式,并引起此问题。
您可以以这种方式禁用它
For Next.js user here like my-self,
strict mode is also enabled by default and causes this issue.
You can disable it in this way
在具有 strictmode 的React应用中:
如果您看到的双控制台日志:
,如果您知道严格模式可以帮助您以某种方式优化应用程序
,并且您不想完全禁用strictmode
:
在严格模式下第二渲染期间为隐藏日志提供了一种选项。为此:
您将不再看到控制台中的双日志。
In a React app with StrictMode:
If you are seeing dual console logs like this:

And if you know that StrictMode helps you optimize your app in some way
And you don't want to disable StrictMode entirely
Then:
The React Developer Tools Chrome Extension offers an option to Hide logs during second render in Strict Mode. To enable that:
You will no more see the dual logs in the console.

如果您使用nextjs,并且要禁用严格的模式,请访问您的
next.config.js
文件,然后将ReactStrictMode设置为false,但建议开发一旦检查双座是否由Double Mount引起,则建议使用严格的模式。稳定的模式最好启用它
if you are using nextjs and you want to disable strict mode go to your
next.config.js
file and set reactStrictMode to falsebut strict mode is recommended for development once you check if the double mount is caused by stric mode it's preferable to enable it
似乎组件呈现两次,但是第一个渲染的组件是不是未置换的?至少那是我与React 17看到的行为,当然可能是我的代码中的错误
It seems the component renders twice, but the first rendered component is not unmounted? At least that is the behaviour I'm seeing with React 17, might a bug in my code of course