[英]How to add "unique key prop" to child using map function
I have seen other people ask similar questions to this and I have tried implementing the answers they received.我看到其他人对此提出了类似的问题,并且我尝试实施他们收到的答案。 But I am still getting a console error.但我仍然收到控制台错误。 I mean the code is working as expected I just hate having console errors.我的意思是代码按预期工作我只是讨厌控制台错误。
Here is my code这是我的代码
const Accordion = () => {
const [clicked, setClicked] = useState(false);
const toggle = index => {
if (clicked === index) {
//if clicked question is already active, then close it
return setClicked(null);
}
setClicked(index);
};
return (
<IconContext.Provider value={{ color: '#441d0c', size: '25px' }}>
<AccordionContainer>
<FaqContainer>
{FaqData.map((item, index) => {
return (
<>
<QuestionWrapper onClick={() => toggle(index)} key={index}>
<h2>{item.question}</h2>
<span>{clicked === index ? <FiMinus /> : <FiPlus />}</span>
</QuestionWrapper>
{clicked === index ? (
<AnswerDropdown>
<p>{item.answer}</p>
</AnswerDropdown>
) : null}
</>
)
})}
</FaqContainer>
</AccordionContainer>
</IconContext.Provider>
)
}
and the console error I get:和我得到的控制台错误:
Warning: Each child in a list should have a unique "key" prop.警告:列表中的每个孩子都应该有一个唯一的“关键”道具。
To me it looks like each child DOES have a unique key, What am I missing?在我看来,每个孩子都有一个唯一的钥匙,我错过了什么?
You are using a React Fragment short syntax that can't have keys.您正在使用不能有键的 React Fragment 短语法。 See: https://reactjs.org/docs/fragments.html#short-syntax请参阅: https://reactjs.org/docs/fragments.html#short-syntax
You have to use the complete syntax:您必须使用完整的语法:
{FaqData.map((item, index) => {
return (
<React.Fragment key={index}>
...
</React.Fragment>
)
})}
The key should be set at the root object of your map.密钥应设置在 map 的根 object 中。 In order to fix the warning, you can replace the react fragment ( <> ) by a div and set the key like this:为了修复警告,您可以将反应片段( <> )替换为 div 并像这样设置键:
{FaqData.map((item, index) => {
return (
<div key={index}>
<QuestionWrapper onClick={() => toggle(index)}>
<h2>{item.question}</h2>
<span>{clicked === index ? <FiMinus /> : <FiPlus />}</span>
</QuestionWrapper>
{clicked === index ? (
<AnswerDropdown>
<p>{item.answer}</p>
</AnswerDropdown>
) : null}
</div>
)
})}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.