在React中,为什么子组件的render函数被调用两次? [英] In React why does a child component's render function get called twice?

查看:57
本文介绍了在React中,为什么子组件的render函数被调用两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拥有最简单的应用程序.有一个父< App> 组件和一个子< MyChildOne> 组件.两者都是基于类的.

I have the simplest of apps. There's a parent <App> component and a child <MyChildOne> component. Both are class-based.

谁能解释为什么React两次调用子< MyChildOne> 的渲染函数?

Can anyone please explain why React calls the render function of child <MyChildOne> twice?

这是我的< App> 代码:

import React from "react";
import "./App.css";
import MyChildOne from "./MyChildOne.js";

class App extends React.Component {
  render() {
    return (
      <div>
        <MyChildOne />
      </div>
    );
  }
}
export default App;

这是我的< MyChildOne> 代码:

import React from "react";

class MyChildOne extends React.Component {
  counter = 0;

  render() {
    this.counter = this.counter + 1;

    console.log(
      "Code has called MyChildOne and this.counter has value: " + this.counter
    );

    return <h1>Hello, {this.counter}</h1>;
  }
}

export default MyChildOne;

浏览器中的输出是这样:

The output in the browser is this:

你好,1

这是在控制台中记录的内容:

And here's what gets logged in the console:

代码已调用MyChildOne,this.counter的值为:1

代码已调用MyChildOne,this.counter的值为:2

很明显,React两次调用< MyChildOne> 的渲染函数-但我不明白为什么!!!

So clearly React is calling the render function of <MyChildOne> twice – but I cannot understand why!!!!

这对我不好,因为我想将道具从< App> 传递到< MyChildOne> 作为道具,而我想要< MyChildOne> 表示该数组的每个事物"成员的< h1> .我不希望< h1> 呈现两次!

This is no good to me because I want to pass as props an array of things from <App> to <MyChildOne> and I want <MyChildOne> to render, let's say, an <h1> for every 'thing' member of that array. I do not want the <h1>s to be rendered twice!

推荐答案

您不必担心多次调用render函数.如果要创建依赖于多次调用render函数的逻辑,则很可能在做错误的事情.最好的办法是您正在执行其他一些逻辑,导致渲染函数被多次调用.

You shouldn't worry too much about the render function being called multiple times. If you're creating logic that depends on the render function being called multiple times, you're most likely doing something wrong. My best would be that you're doing some other logic that causes the render function to being called multiple times.

您应该注意,如果您的父组件重新渲染,则您的子组件也会重新渲染.我为您提供的代码创建了一个最小的示例,这清楚地表明您的问题在其他地方. https://codesandbox.io/s/react-example-6ud9d

You should note that if your parent component re-renders, so does your child component. I created a minimal example of the code you provided, which makes it clear that your issue is somewhere else. https://codesandbox.io/s/react-example-6ud9d

这篇关于在React中,为什么子组件的render函数被调用两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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