我得到以下警告消息,这是说,我需要一个唯一的密钥道具。
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 + style -component,在这些例子中,快捷选择是一个样式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)
输出本身正在工作并且功能齐全。然而,我很困惑为什么我得到了一个独特的钥匙道具警告,尽管我在每个组件里面都有钥匙。我错过什么了吗?
如需其他资料,请告知。
你应该指定映射的元素的父元素的关键,在你的情况中:
return (<>
{
options.map((item, index) =>
<div key={index}>
<h2 >{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>
)}
</div>
)
}
</>)
}