【发布时间】:2021-12-02 18:13:06
【问题描述】:
我收到以下警告消息,表示我需要一个唯一的密钥道具。
front_1 | Warning: Each child in a list should have a unique "key" prop. See https://reactjs.org/link/warning-keys for more information.
front_1 | at ShortcutArea (webpack-internal:///./components/encoding/ShortcutArea.tsx:38:5)
front_1 | at div
front_1 | at I (/app/node_modules/styled-components/dist/styled-components.cjs.js:1:19218)
front_1 | at div
front_1 | at I (/app/node_modules/styled-components/dist/styled-components.cjs.js:1:19218)
front_1 | at EncodingIndexPage (webpack-internal:///./pages/techutils/encoding/index.tsx:83:72)
front_1 | at div
front_1 | at I (/app/node_modules/styled-components/dist/styled-components.cjs.js:1:19218)
front_1 | at div
front_1 | at I (/app/node_modules/styled-components/dist/styled-components.cjs.js:1:19218)
front_1 | at Layout (webpack-internal:///./components/common/Layout.tsx:41:3)
front_1 | at GlobalProvider (webpack-internal:///./libs/context/GlobalProvider.tsx:49:3)
front_1 | at MyApp (webpack-internal:///./pages/_app.tsx:36:3)
front_1 | at ae (/app/node_modules/styled-components/dist/styled-components.cjs.js:1:13294)
front_1 | at AppContainer (/app/node_modules/next/dist/server/render.js:293:29)
但是,我碰巧为里面的每个组件都有一个唯一的键。我正在使用 Next.js + styled-component,在这些示例中,ShortcutSelection 是一个样式化的 div,如果在这种情况下这可能是相关位的话。
const ShortcutSelection = styled.div`
color: rgba(0,0,0,0.5);
:hover {
background-color : rgba(0,0,0,0.05);
cursor : pointer;
color : rgba(0,0,0,0.8);
font-weight : 600;
}
代码:
export default function ShortcutArea({handler, ...props}){
const ShortcutClickHandler = (e) => {
handler.setEncoding(e);
}
return (<>
{
options.map((item, index) =>
<>
<h2 key = {index}>{item.title}</h2>
{item.data.map((shortcut,idx) =>
<ShortcutSelection key = {index + "_" + idx}
onClick={ShortcutClickHandler}
data-currentencoding={shortcut.from}
data-targetencoding={shortcut.to}
data-payload={shortcut.payload}
data-action={shortcut.action}
>{shortcut.displaytext}
</ShortcutSelection>
)}
</>
)
}
</>)
}
options 是一个javascript 对象数组,每个item 都有data,这也是一个由javascript 对象组成的数组,因此我感觉需要嵌套映射。选项示例如下所示:
const options = [
{
"title" : "List of fruits",
"data" : [
{
"displaytext" : "Apple",
"description" : "This Apple is quite delicious"
},
{
"displaytext" : "Banana",
"description" : "Banana is also quite good"
},
]
},
{
"title" : "List of Veggies",
"data" : [
{
"displaytext" : "lettuce",
"description" : "It's a lettuce!"
}
]
},
]
所以结果是这样的:
List of fruits (h2)
Apple (styled with ShortcutSelection)
Banana (styled)
List of Veggies (h2)
lettuce (styled)
输出本身正在工作并且功能齐全。但是,尽管我在内部的每个组件中都有密钥,但我对为什么会收到唯一的密钥道具警告感到困惑。我有什么遗漏吗?
如果需要任何其他信息,请告诉我。
【问题讨论】: