简体   繁体   English

组件渲染两次(reactJS)

[英]Component render two times (reactJS)

I have a React Component, when I compile it it renders two times.我有一个 React 组件,当我编译它时它会渲染两次。 Some idea?有什么想法?

import React, { useState } from "react";
export default () => {
  const [loaded, setLoaded] = useState(false);
  return (
    <>
      {console.log("test")}
      {alert("y")}
      <h2>Cargando</h2>
    </>
  );
}

You are probably using React.StrictMode , right?您可能正在使用React.StrictMode ,对吧?

Read about it here https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects在这里阅读https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects

It has special mechanism to detect side-effects so in development mode some components will render 2 times instead of one.它具有检测副作用的特殊机制,因此在开发模式下,某些组件将渲染 2 次而不是 1 次。 But it could also happen in production unintentionally but you really should not care about how many times render happened.但它也可能在生产中无意中发生,但你真的不应该关心渲染发生了多少次。

How do you know that it renders two times?你怎么知道它渲染了两次? Because of console.log?因为console.log? It just means that inner mechanisms of react call rendering two times... You should not care about it.它只是意味着反应调用渲染的内部机制两次......你不应该关心它。 It can be called even 10 times if necessary必要时甚至可以调用 10 次

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

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