React代码示例,由于缺少键而存在错误?

huangapple go评论61阅读模式
英文:

Minimal example React code which is buggy due to the lack of keys?

问题

Sure, here's the translation of the code snippet you provided:

我是React的新手尝试理解组件的`key`属性

根据[官方文档](https://react.dev/learn/rendering-lists#rules-of-keys)(我强调),

> *你可能会诱惑使用数组中的项目索引作为其键事实上如果您不指定键React将使用这种方式但是如果插入删除项目或重新排序数组呈现项目的顺序会随时间而改变**索引作为键通常会导致微妙且令人困惑的错误***

但是除了性能问题之外还可能出现什么样的错误呢

我想看一个具体的示例代码由于缺少`key`属性而出现错误而不是像它会出错这样的抽象文本说明

例如下面的代码在没有使用`key`的情况下按预期工作[CodeSandbox](https://codesandbox.io/embed/admiring-bessie-pmsuw1?fontsize=14&hidenavigation=1&theme=dark)):

```react
import { useState } from "react";

export default function MyApp() {
    const [l, setL] = useState([
        {
            id: 0,
            name: "Apple",
        },
        {
            id: 1,
            name: "Orange",
        },
        {
            id: 2,
            name: "Grapes",
        },
    ]);

    return (
        <>
            <ul>
                {
                    l.map(e => {
                        return (
                            <div>
                                <li>{e.name}</li>
                                <button onClick={() => {
                                    const index = l.indexOf(e);
                                    let ll = [...l];
                                    ll.splice(index, 1);
                                    setL(ll);
                                }}>x</button>
                            </div>
                        );
                    })
                }
            </ul>
        </>
    );
}

希望这能帮助您理解代码。

英文:

I'm a newbie to React and trying to understand key attribute of components.

According to the official documentation (emphasis mine),

> You might be tempted to use an item’s index in the array as its key. In fact, that’s what React will use if you don’t specify a key at all. But the order in which you render items will change over time if an item is inserted, deleted, or if the array gets reordered. Index as a key often leads to subtle and confusing bugs.

but what kind of bugs can appear in addition to performance issue?

I'd like to see a concrete example code which is buggy due to the lack of key attribute, rather than an abstract textual explanation like "it would be buggy".

For example, the code below works as expected without the use of key (CodeSandbox):

import {useState} from &quot;react&quot;;

export default function MyApp() {
    const [l, setL] = useState([
        {
            id: 0,
            name: &quot;Apple&quot;,
        },
        {
            id: 1,
            name: &quot;Orange&quot;,
        },
        {
            id: 2,
            name: &quot;Grapes&quot;,
        },
    ]);

    return (
        &lt;&gt;
            &lt;ul&gt;
                {
                    l.map(e =&gt; {
                        return (
                            &lt;div&gt;
                                &lt;li&gt;{e.name}&lt;/li&gt;
                                &lt;button onClick={() =&gt; {
                                    const index = l.indexOf(e);
                                    let ll = [...l];
                                    ll.splice(index, 1);
                                    setL(ll);
                                }}&gt;x&lt;/button&gt;
                            &lt;/div&gt;
                        );
                    })
                }
            &lt;/ul&gt;
        &lt;/&gt;
    );
}

答案1

得分: 1

如果您不指定任何键,React将默认使用'index'作为键。在这个代码沙箱示例中,第一个表格中的代码使用'index'作为键,而第二个表格中的代码使用'unique id'作为键。

您会注意到,在第一个表格中,如果删除一行,它会在3秒后删除该行,但不会从行中删除'deleting..'状态,而是将其放在现在具有先前行索引的下一行。

由于组件的索引可能在运行时更改,我们应该避免使用索引以避免在运行时出现这种错误。这也会导致许多性能问题。我认为您已经从您的研究中发现了这些问题。祝您在学习过程中一切顺利。希望这个答案对您有帮助。

要了解更多,请阅读这篇文章:在React应用程序中为什么不应该使用Array 'index'作为'key'

英文:

If you don't specify any key React will specify 'index' as the key by default.
Here is a code sandbox example where the code use 'index' as the key in the first table and 'unique id' as the key in the second table:

React代码示例,由于缺少键而存在错误?

You will notice that in the first table if you delete a row, it deletes it after 3 sec, but instead of removing 'deleting..' status from the row, it places it on the next row that now has the index of the previous row.

As an index of the component can change in run time, we should avoid using the index to avoid this kind of error in run time. It also has many performance issues. I think you already found those from your research. All the best for your learning journey. I hope this answer was helpful.

To learn more read this article: Reiterating why you should never use Array ‘index’ as ‘key’ in your React Applications

答案2

得分: 0

希望这篇文章可以帮助理解关键的作用,深入了解React关键问题

英文:

Hope this article can help understand the role of key,Deep dive into React keys bugs

huangapple
  • 本文由 发表于 2023年5月10日 14:16:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76215376.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定