reactjs - 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"));
解决方案
这是因为您的 Child 组件 ieChild1
和Child2
使用与 相同的值key
。counter
和状态都counter2
具有相同的值,这会在 ReactDOM 中产生歧义。在这里,您没有迭代 an array
,因此不需要使用该key
属性。它会正常工作。如果您必须使用该key
属性,请确保它们在同一级别是唯一的。
~Prayag
推荐阅读
- .net - 在 Azure Pipelines 上构建 .NET Core 3.0
- java - java.lang.NoClassDefFoundError: org.jumpmind.symmetric.io.stage.StagingManager$1,即使 jar 文件中存在该类
- dji-sdk - 我可以在没有 GPS 的情况下使用 DJI SDK 计划任务吗?
- wordpress - 关于价格变化和为产品添加新属性的问题
- sql - 如何将 postgres 函数的结果保存到变量中?
- java - 如何在recyclerview中选择选定值多值
- javascript - 使用异步在 Node JS 中一个接一个地下载视频?
- linux - 如何使用 awk 命令检索特定单词
- node.js - 如何使用 nodejs SDK 为 google firestore 收集数据创建 REST API
- python - 一个奇怪的属性发生了,当我使用 super() 从另一个类扩展时