React的列表组件必须要有key?

React警告列表组件需设置key属性以提升性能。key帮助React识别元素变化,避免不必要的渲染。key值不传递给组件,需通过其他属性如id获取。key在兄弟节点间需唯一。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、列表组件没有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')
);

参考文档
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值