React学习-列表循环中的特殊属性key
来源:互联网 发布:清朝留辫子原因 知乎 编辑:程序博客网 时间:2024/06/06 19:02
一、key的作用
1. key 帮助react确定list中哪些item已更改,添加或删除。
2. 便于在dom变化后,对比新旧DOM具体哪些item已变化,加快虚拟dom渲染和性能提升
二、key的使用注意事项
1. 使用数组下标做key是不被推荐的,如果遇到数组排序的情况下,将降低渲染性能。
const todoItems = todos.map((todo, index) => // 只有在没有id的情况下,才考虑使用数组下标 <li key={index}> {todo.text} </li>);
2.数组中的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'));
3.key的值无法传递到子组件中,若要实现相同数据的传递,可使用其他名称作为属性名。访问key的值会返回undefined
const content = posts.map((post) => <Post key={post.id} id={post.id} title={post.title} />);
阅读全文
1 0
- React学习-列表循环中的特殊属性key
- react中的key属性与angular中的index属性
- zabbix-agent key属性列表
- zabbix-agent key属性列表
- zabbix-agent key属性列表
- zabbix-agent key属性列表
- TableLayout中的特殊属性
- 微信小程序 wx:key 高级列表循环
- React-数据列表渲染学习
- react入坑之列表和key(索引)
- React 有状态组件及 key 属性的应用
- 浅谈React的diff算法和key属性
- 列表渲染多层嵌套循环及wx:key的使用
- React学习之列表运用(七)
- React学习笔记实战1:todo列表
- GridView xml文档中的特殊属性
- Python中的特殊方法、属性和迭代器
- react-router的 <Link/>中的属性
- c# 自定义配置文件
- Docker的“下一跳”在哪里?
- Ubuntu更换阿里源
- MySQL之——SQL按照汉字首字母进行搜索排序
- 神经网络
- React学习-列表循环中的特殊属性key
- Android自定义View的事件分发机制(三)
- notes
- buf_flush_page_cleaner_thread
- HTML基础总结
- HDU5122-对冒泡的理解||BIT
- 异常链,异常嵌套
- std::bind
- eclipse.exe启动的时候,为什么需要指定jre?或者说,如果没有jre,为什么eclipse.exe就运行不起来,或者报错?