【问题标题】:Why does the render function in react is called twice when using the component strategy?为什么在使用组件策略时react中的render函数会被调用两次?
【发布时间】:2020-10-31 04:40:51
【问题描述】:

我是新手,如何理解为什么在渲染函数内部时 console.log 被调用两次?

import React, { Component } from "react";
import "./App.css";

class App extends Component {

  render() {
    console.log("Prints twice in console");
    return (
      <div className="App">

      </div>
    );
  }
}

export default App;

好像我不从组件扩展并使用函数,而是控制台只打印一次

import React from "react";
import "./App.css";
function App() {
  console.log("prints once");
  return <div className="App"></div>;
}

export default App;

【问题讨论】:

  • 我可能会补充说,这不是调试应用程序的最佳方式。 React 本身可能会在它认为合适时重新渲染您的组件
  • 在这篇文章中有人深入讨论了双重渲染:mariosfakiolas.com/blog/…
  • 感谢 dejoma - 这篇文章提供了帮助。

标签: reactjs react-component


【解决方案1】:

检查 ./src 目录中的 index.js。我认为它会在

中呈现 App 组件
<React.StrictMode>

删除它,它会停止渲染函数两次。

您也可以查看This

【讨论】:

    猜你喜欢
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 2018-05-18
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多