您现在的位置是:首页 > Javascript
当前栏目
React的列表组件必须要有key?
2023-03-20 14:51:55 时间
一、列表组件没有key属性会warning?
1、key提高性能
当创建列表组件时,必须给每一个元素设置 key 属性,否则会有警告: a key should be provided for list items。如果元素没有key属性,React很难判断元素应该怎么渲染?如果元素有key值,那么React只对匹配key值的元素,进行更改等渲染操作,这样极高提升了运行性能。
二、列表组件使用说明
1、错误用法
function ListItem(props) {
const value = props.value;
return (
// 错误!你不需要在这里指定 key:
<li key={value.toString()}>
{value}
</li>
);
}
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) =>
// 错误!元素的 key 应该在这里指定:
<ListItem value={number} />
);
return (
<ul>
{listItems}
</ul>
);
}
const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
<NumberList numbers={numbers} />,
document.getElementById('root')
);
2、正确用法
function ListItem(props) {
// 正确!这里不需要指定 key:
return <li>{props.value}</li>;
}
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) =>
// 正确!key 应该在数组的上下文中被指定
<ListItem key={number.toString()} value={number} />
);
return (
<ul>
{listItems}
</ul>
);
}
const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
<NumberList numbers={numbers} />,
document.getElementById('root')
);
3、key值无法读取
key 值会传递给 React ,但不会传递给组件。如果需要使用 key 值,请用其他属性(譬如id):
# Post 组件可以读出 props.id,但是不能读出 props.key
const content = posts.map((post) =>
<Post
key={post.id}
id={post.id}
title={post.title} />
);
4、唯一性
key 在兄弟节点间必须唯一,但全局不需要唯一。
function Blog(props) {
const sidebar = (
<ul>
{props.posts.map((post) =>
<li key={post.id}>
{post.title}
</li>
)}
</ul>
);
const content = props.posts.map((post) =>
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.content}</p>
</div>
);
return (
<div>
{sidebar}
<hr />
{content}
</div>
);
}
const posts = [
{ id: 1, title: 'Hello World', content: 'Welcome to learning React!' },
{ id: 2, title: 'Installation', content: 'You can install React from npm.' }
];
ReactDOM.render(
<Blog posts={posts} />,
document.getElementById('root')
);
参考文档
相关文章
- React Native中加载指示器组件ActivityIndicator使用方法
- Cesium 组件重写
- EasyCVR如何添加流量统计功能?
- JSBridge 技术原理分析
- HTTP跨域请求后台处理
- 五分钟带你入门基于Nodejs的强大的Web框架— NestJS
- Spring Boot 面试杀手锏:自动配置原理
- Web-Hacking-ToolKit:一款带有GUI的Web安全测试Docker镜像
- FreeBuf周报 | 成人视频网站StripChat数据库泄漏;macOS曝出零日漏洞
- LeetCode笔记:492. Construct the Rectangle
- CSS 基础知识
- 每次新增页面复制粘贴?100多行源码的 element-ui 的新增组件功能教你解愁
- Flutter 控件布局
- 面向数据的架构
- HTTP中Origin和Referer的区别?
- JavaScript 高频函数优化-函数防抖&函数节流
- js 动态修改_after_before伪元素content值
- JS中DOM事件流总结
- Electron快速上手并将网站直接生成桌面应用
- 分享 12 个重要的 JS 函数,建议每个前端开发人员都要搞清楚