当前位置: 首页 > java >正文

React之旅-05 List Key

每个React的初学者,在调试程序时,都会遇到这样的警告:Warning: Each child in a list should have a unique "key" prop. 如下面的代码:

const list = ['Learn React', 'Learn GraphQL'];const ListWithoutKey = () => (<div><ul>{list.map((item) => (<li>{item}</li>))}</ul></div>
);

这个警告提示我们,需要为列表中的每个元素添加 key 属性。如下面的代码:

const ListWithoutKey = () => (<div><ul>{list.map((item, index) => (<li key={index}>{item}</li>))}</ul></div>
);

使用上面的代码调试时,之前的警告会消失,但其实在其背后,有一个隐式的 bug。当你对列表进行重新排序时,特别是当你添加了非受控的元素,问题就会发生。

如果你的代码如下:

const initialList = ['Learn React', 'Learn GraphQL'];const ListWithUnstableIndex = () => {const [list, setList] = React.useState(initialList);const handleClick = event => {setList(list.slice().reverse());};return (<div><ul>{list.map((item, index) => (<li key={index}><label>{item}</label></li>))}</ul><button type="button" onClick={handleClick}>Reverse List</button></div>);
};

运行你的代码,点击按钮对列表进行重新排序,看样子,一切正常。

可是当你添加了不受控的元素时,假如你的代码如下:

const initialList = ['Learn React', 'Learn GraphQL'];const ListWithUnstableIndex = () => {const [list, setList] = React.useState(initialList);const handleClick = event => {setList(list.slice().reverse());};return (<div><ul>{list.map((item, index) => (<li key={index}><label><input type="checkbox" />{item}</label></li>))}</ul><button type="button" onClick={handleClick}>Reverse List</button></div>);
};

在上述的代码中,checkbox 是非受控元素,当你运行上述的代码时,运行的结果,可能和你相像的不太一致。

// 列表最初的样子[x] Learn React
[ ] Learn GraphQL// 点击按钮,列表重新排序后的样子[x] Learn GraphQL
[ ] Learn React

这种结果显然不是你想要的,那这背后终究发生了什么呢?

// 列表当初的样子[x] Learn React (index = 1)
[ ] Learn GraphQL (index = 2)// 点击按钮,列表重新排序后的样子[x] Learn GraphQL (index = 1)
[ ] Learn React (index = 2)

那如何解决这个问题呢,办法当然有,这次,我们使用了相当稳定的元素作为 key 属性。代码如下:

const initialList = [{ id: 'a', name: 'Learn React' },{ id: 'b', name: 'Learn GraphQL' },
];const ListWithStableIndex = () => {const [list, setList] = React.useState(initialList);const handleClick = event => {setList(list.slice().reverse());};return (<div><ul>{list.map(item => (<li key={item.id}><label><input type="checkbox" />{item.name}</label></li>))}</ul><button type="button" onClick={handleClick}>Reverse List</button></div>);
};

点击按钮,列表重新排序后,背后发生了变化。

// 列表最初的样子
[x] Learn React (id = a)
[ ] Learn GraphQL (id = b)// 点击按钮,列表重新排序后的样子[ ] Learn GraphQL (id = b)
[x] Learn React (id = a)

在这里,我们使用了 id 作为 key 属性,当然,你也可以使用列表中的其他元素,但前提是这个元素是不可改变的唯一值。

不管怎样,仍然值得注意的是,只要你的列表保持的顺序或大小没有改变,使用索引是可以的。然后,列表中每个项目的位置不会改变——它与索引一样稳定——因此使用索引是可以的。

原文链接:Why do we need a React List Key

http://www.xdnf.cn/news/15053.html

相关文章:

  • 力扣 hot100 Day40
  • Java 大视界 -- Java 大数据在智能交通智能停车诱导与车位共享中的应用(341)
  • AI翻唱——So-VITS-SVC
  • mvn能只test单独一个文件吗
  • 攻防世界——web题catcat-new session值伪造
  • 电脑息屏工具,一键黑屏超方便
  • 【LeetCode100】--- 1.两数之和【复习回滚】
  • 学习日记-spring-day45-7.10
  • 深入理解 Linux 中的 stat 函数与文件属性操作
  • 710 Mybatis实战
  • Using Spring for Apache Pulsar:Transactions
  • PyTorch Tensor 操作入门:转换、运算、维度变换
  • 【TCP/IP】11. IP 组播
  • 深入解析JVM内存结构与垃圾回收机制
  • Boost.Asio学习(3):异步读写
  • Spring for Apache Pulsar->Reactive Support->Message Production
  • Linux的DNS域名解析服务
  • 多线程 JAVA
  • 表达式索引海外云持久化实践:关键技术解析与性能优化
  • 深入浅出 Python Asynchronous I/O:从 asyncio 入门到实战
  • 2025.07.09华为机考真题解析-第二题200分
  • FlashAttention 快速安装指南(避免长时间编译)
  • LeetCode经典题解:49、字母异位词分组
  • 西部数据WD授权代理商-深圳同袍存储科技有限公司
  • 5种使用USB数据线将文件从安卓设备传输到电脑的方法
  • Sophix、Tinker 和 Robust 三大主流 Android 热修复框架的详细对比
  • C语言顺序表:从零开始,解锁数据结构之门!
  • 无人机三叶螺旋桨概述
  • git fetch的使用
  • OpenSearch 视频 RAG 实践