首页 > 解决方案 > React Components 子组件渲染两次 - 有什么方法可以解决这个问题?

问题描述

When i click on Update Key button then Child1 component render every time so how can i resolve it.  
Note : I have create three component one parent component and two child component when i click on 
       parent component button to update child component, so child1 component increase to display 
       multiple time. so please resolved this as soon as possible.

当我单击更新密钥按钮时,Child1 组件每次都会渲染,所以我该如何解决它。
注意:当我单击父组件按钮更新子组件时,我创建了三个组件一个父组件和两个子组件,因此 child1 组件增加以显示多次。所以请尽快解决这个问题。

import React, { useState } from "react";
import ReactDOM from "react-dom";

class Child1 extends React.Component {
  componentDidMount() {
    console.log("mounted");
  }
  render() {
    console.log("rendered");
    return <div>Child</div>;
  }
}

class Child2 extends React.Component {
  componentDidMount() {
    console.log("mounted2");
  }
  render() {
    console.log("rendered2");
    return <div>Child2</div>;
  }
}

class App extends React.Component {
  state = {
    counter: 0,
    counter2: 0
  };

onCounter = () => this.setState({ counter: this.state.counter + 1 , counter2: this.state.counter2 + 1 });

  render() {
    return (
      <>
        <Child1 key={this.state.counter} />
        <Child2 key={this.state.counter2} />
        <button onClick={this.onCounter}>Update Key</button>
      </>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

标签: reactjs

解决方案


这是因为您的 Child 组件 ieChild1Child2使用与 相同的值keycounter和状态都counter2具有相同的值,这会在 ReactDOM 中产生歧义。在这里,您没有迭代 an array,因此不需要使用该key属性。它会正常工作。如果您必须使用该key属性,请确保它们在同一级别是唯一的。

~Prayag


推荐阅读