react异常 Each child in a list should have a unique “key” prop

2023-07-11,,

react异常警告:Each child in a list should have a unique “key” prop

原因:Dom在渲染数组时,需要一个key,不然嵌套数组时会引起歧义

解决:

1   <div className="classlist-contaier">
2 {this.state.classList.map((item, index) => {
3 return <ClassItem key={index}/>;
4 })}
5 </div>

另外,如果遍历添加组件时,在组件外再加个div之类的容器,那么key需要在上层添加。比如:

1   <div className="classlist-contaier">
2 {this.state.classList.map((item, index) => {
3 return (
4 <div key={index}>
5 <ClassItem/>
6 </div>
7 );
8 })}
9 </div>

react异常 Each child in a list should have a unique “key” prop的相关教程结束。

《react异常 Each child in a list should have a unique “key” prop.doc》

下载本文的Word格式文档,以方便收藏与打印。