react 警告消除警告:列表中的每个子项都应该有一个唯一的“key” Prop 。
我想消除 「警告:列表中的每个 child 都应该有一个唯一的“key” Prop 。」
代码如下
import { useState } from "react";
const SIZE_ARRAY = [
{
label: "Small",
value: "sm"
},
{
label: "Medium",
value: "md"
},
{
label: "Large",
value: "lg"
}
];
const DEVICE_ARRAY = [
{
deviceLabel: "PC",
deviceValue: "pc"
},
{
deviceLabel: "Tablet",
deviceValue: "tablet"
},
{
deviceLabel: "Mobile",
deviceValue: "mobile"
}
];
export default function SampleLoop() {
const [option, setOption] = useState();
return (
<>
<ul>
{SIZE_ARRAY.map((size) => {
const { label, value } = size;
return (
<li key={label}>
<span>Margin : {label}</span>
{DEVICE_ARRAY.map((device) => {
const { deviceLabel, deviceValue } = device;
return (
<>
<input
key={deviceLabel}
onChange={(newValue) => {
setOption({
...option,
margin_size: {
...option.margin_size,
[value]: {
...option.margin_size[value],
[deviceValue]: newValue
}
}
});
}}
/>
</>
);
})}
</li>
);
})}
</ul>
</>
);
}
它是两个循环的嵌套形式。
是否有不同的位置来连接 KEY?
最佳答案
在这里:
{DEVICE_ARRAY.map((device) => {
const { deviceLabel, deviceValue } = device;
return (
<>
<input
key={deviceLabel}
onChange={(newValue) => {
setOption({
...option,
margin_size: {
...option.margin_size,
[value]: {
...option.margin_size[value],
[deviceValue]: newValue
}
}
});
}}
/>
</>
);
})}
每个子元素的“根元素”是 </>
,即<Fragment/>
,不是<input/>
。所以你应该在前者中定义键。虽然坦率地说,你不需要那个 Fragment
除非您在发布的代码中省略了某些组件。
顺便说一句,如果您在其中指定了任何 Prop ,则无法使用片段简写。 即这不起作用:
< key={deviceLabel}>
</>
相反,这样做
<Fragment key={deviceLabel}>
</Fragment>
关于javascript - react 警告消除警告: Each child in a list should have a unique "key" prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72740964/