[英]React Warning eliminate Warning: Each child in a list should have a unique "key" prop
React 警告消除警告:列表中的每個孩子都應該有一個唯一的“關鍵”道具。
我想消除“警告:列表中的每個孩子都應該有一個唯一的“關鍵”道具。”
代碼如下
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
。
順便說一句,如果您在其中指定任何道具,則不能使用片段速記。 即這不起作用:
< key={deviceLabel}>
</>
相反,這樣做
<Fragment key={deviceLabel}>
</Fragment>
刪除<input>
周圍的冗余片段
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>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.