[英]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.