My React Component is rendering twice because of Strict Mode

岁酱吖の 提交于 2020-06-25 02:11:08

问题


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

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


回答1:


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:

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

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

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



回答2:


Yes you have to remove Strict mode as

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.



来源:https://stackoverflow.com/questions/61254372/my-react-component-is-rendering-twice-because-of-strict-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!