列表中的每个子项都应该有一个唯一的“key”道具——但他们已经这样做了(每次迭代有两个子项)

问题描述 投票:0回答:1

这个问题与类似的问题不同,因为据我所知,所有其他这种性质的问题确实没有唯一的钥匙让所有孩子都被

map
'd。

这是我的代码...

首先,为了更好地衡量,我有这个检查,所以毫无疑问每个键都是唯一的:

    const nbItems = items.length
    const nbUniqueUuids = new Set(items.map((item) => item.uuid)).size
    if (nbItems !== nbUniqueUuids) {
        throw new Error("Non-unique UUIDs detected")
    }

然后,我在组件的 return 语句中执行此操作:

{items.map((item, index) => {
                return (
                    <>
                        {index !== 0 && (
                            <Xarrow
                                key={`${item.uuid}-arrow`}
                                start={item.uuid}
                                end={items[index - 1].uuid}
                            />
                        )}
                        <Item
                            key={item.uuid}
                            action={item}
                        />
                    </>
                )
            })}

如您所见,渲染了两个元素:

Xarrow
Item
。然而,每个密钥都有自己的密钥:一个带有
-arrow
后缀,另一个没有。
uuid
属性已确认是唯一的,否则 if 语句将触发并引发错误。

为什么 React 认为这里有一个非唯一的子元素,而显然每个子元素都有一个唯一的

key

具体的错误信息是:

Warning: Each child in a list should have a unique "key" prop. Check the render method of MyExampleComponent.
这里的“MyExampleComponent”确认就是这个。
Xarrow
Item
都不会渲染任何子项。

如果我将两个项目都包裹在

div
中并给 it
key
,它可以工作,但我不想这样做。

我还会注意到,这可以正常工作,但我仍然在控制台中收到错误。

javascript reactjs react-dom
1个回答
0
投票

结果我必须将

key
赋予片段 (
<></>
),为了做到这一点,我必须使用完整的片段语法:
<React.Fragment key={item.uuid}>...</React.Fragment>

© www.soinside.com 2019 - 2024. All rights reserved.