由于严格模式,我的 React 组件渲染了两次 [英] My React Component is rendering twice because of Strict Mode

查看:177
本文介绍了由于严格模式,我的 React 组件渲染了两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 React 组件渲染了两次.所以,我决定逐行调试,问题就在这里

My React Component is rendering twice. So, I decided to do a line by line debug and the problem is here

 if ( workInProgress.mode & StrictMode) {
        instance.render();
      }

React-dom.development.js

React-dom.development.js

是不是因为严格模式?我可以禁用它吗?什么是严格模式?我需要吗?

Is it because of strict mode? can I disable it? What is Strict mode? Do I need it?

推荐答案

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).

如果您在应用中启用了 StrictMode 但不记得启用它,可能是因为您最初使用 create-react-app 或类似工具创建应用,默认情况下会自动启用 StrictMode.

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.

例如,您可能会发现您的 {app} 在 index.js 中被 包裹:

For example, you might find that your {app} is wrapped by <React.StrictMode> in your index.js:

  ReactDOM.render(
     <React.StrictMode>
       {app}
     </React.StrictMode>,
    document.getElementById('root')
  );

如果是这样,您可以通过移除 标签来禁用 StrictMode:

If so, you can disable StrictMode by removing the <React.StrictMode> tag:

  ReactDOM.render(
    {app}
    document.getElementById('root')
  );

这篇关于由于严格模式,我的 React 组件渲染了两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆