[英]Give unique key props to react nested map
如何在反应地图中给出唯一的关键道具。 我使用 uuidv4 库,但 react 还说每个子组件都应该有一个唯一的 key prop。 这是我使用 uuidv4 npm 库的代码。
我尝试了很多方法,但它不起作用。
// import Sidebar from '../components/Sidebar'
import React from 'react'
import Navbar from '../components/Navbar';
import ButtonGroup from '../components/ButtonGroup';
import MCQS from '../components/MCQ';
import { Outlet } from 'react-router';
import { v4 as uuidv4 } from 'uuid';
import { useSelector } from 'react-redux';
const C_P_HOME = () => {
const { heading } = useSelector(state => state.heading);
const { questions } = useSelector(state => state.question);
return (
<>
<Navbar isContainerTrue={false} />
<div className='grid grid-cols-12 '>
<div className="col-span-6 bg-slate-100 grid grid-cols-12 p-8 h-screen items-baseline">
<ButtonGroup />
<Outlet />
</div>
<div className="col-span-6 bg-slate-200 h-screen overflow-y-scroll">
<div className="heading select-none">
<h1 className='text-2xl text-center font-bold mt-8'>{heading}</h1>
</div>
<div className="questions p-8">
{
questions.map((q, index) => {
return (
<>
<h2 className='text-2xl font-semibold' key={uuidv4()}>Q:{(index + 1) + " " + q.heading}</h2>
<ol className='list-[lower-roman]' key={uuidv4()}>
{
q.questions.map((ques, index) => {
return (
<>
<li className='text-lg ml-16' key={uuidv4()}>{ques}</li>
</>
)
})
}
</ol>
</>
)
})
}
</div>
</div>
</div>
</>
)
}
export default C_P_HOME;
这是我的错误截图。
谢谢我得到了答案。
通常,遍历数组等时的键应该来自数组本身中的每个项目。 假设您的question
有一个id
,您想使用该id
作为key
。 由于 id 通常是唯一的,因此除非它是 f.ex,否则该项目的此密钥不会更改。 移除
尝试使用下面的代码。 我使用索引和问题内容创建了键。
{
questions.map((q, index) => {
return (
<div key={`${index}_${JSON.stringify(q)}`}>
<h2 className='text-2xl font-semibold'>
Q:{index + 1 + ' ' + q.heading}
</h2>
<ol className='list-[lower-roman]'>
{q.questions.map((ques, i) => (
<li className='text-lg ml-16' key={`${ques}_${i}`}>
{ques}
</li>
))}
</ol>
</div>
);
});
}
你的问题在这里
q.questions.map((ques, index) => {
return (
<>
<li className='text-lg ml-16' key={uuidv4()}>{ques}</li>
</>
)
关键属性需要在map
内的容器元素上
只需删除<> </>
q.questions.map((ques, index) => <li className='text-lg ml-16' key={uuidv4()}>{ques}</li>)
或使用React.Fragment
q.questions.map((ques, index) => {
return (
<React.Fragment key={uuidv4()}>
<li className='text-lg ml-16' >{ques}</li>
</React.Fragment>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.