[英]How to add "unique key prop" to child using map function
我看到其他人对此提出了类似的问题,并且我尝试实施他们收到的答案。 但我仍然收到控制台错误。 我的意思是代码按预期工作我只是讨厌控制台错误。
这是我的代码
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>
)
}
和我得到的控制台错误:
警告:列表中的每个孩子都应该有一个唯一的“关键”道具。
在我看来,每个孩子都有一个唯一的钥匙,我错过了什么?
您正在使用不能有键的 React Fragment 短语法。 请参阅: https://reactjs.org/docs/fragments.html#short-syntax
您必须使用完整的语法:
{FaqData.map((item, index) => {
return (
<React.Fragment key={index}>
...
</React.Fragment>
)
})}
密钥应设置在 map 的根 object 中。 为了修复警告,您可以将反应片段( <> )替换为 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.