[英]Missing "key" prop for element in iteratoreslintreact/jsx-key
The following part is returning Missing "key" prop for element in iteratoreslintreact/jsx-key
以下部分
Missing "key" prop for element in iteratoreslintreact/jsx-key
{[...Array(10)].map((_) => (
<Skeleton variant="rectangular" sx={{ my: 4, mx: 1 }} />
))}
I tried to fix it as following:我试图按如下方式修复它:
{[...Array(10)].map((x) => (
<Skeleton variant="rectangular" sx={{ my: 4, mx: 1 }} key="x.id" />
))}
but I'm not quite sure if it's correct.但我不太确定它是否正确。
import { useState, useEffect } from 'react';
import type { NextPage } from 'next';
import Container from '@mui/material/Container';
import Box from '@mui/material/Box';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import { Card, Paper } from '@mui/material';
import Skeleton from '@mui/material/Skeleton';
import { amber, orange } from '@mui/material/colors';
import FormOne from './../src/FormOne';
const columns: GridColDef[] = [
{ field: 'id', headerName: 'ID' },
{ field: 'title', headerName: 'Title', width: 300 },
{ field: 'body', headerName: 'Body', width: 600 },
];
const LoadingSkeleton = () => (
<Box
sx={{
height: 'max-content',
}}
>
{[...Array(10)].map((_) => (
<Skeleton variant="rectangular" sx={{ my: 4, mx: 1 }} />
))}
</Box>
);
const Home: NextPage = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
// fetch data from fake API
useEffect(() => {
setInterval(
() =>
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((data) => {
setPosts(data);
setLoading(false);
}),
3000
);
}, []);
return (
<Container
maxWidth={false}
sx={{
height: '100vh',
overflow: 'auto',
paddingRight: '0px !important',
paddingLeft: '0px !important',
background: `linear-gradient(to right, ${amber[300]}, ${orange[500]})`,
}}
>
<Card
sx={{ marginBottom: 10, padding: 10, marginLeft: 25, marginRight: 25 }}
>
<FormOne />
</Card>
<Card sx={{ marginLeft: 25, marginRight: 25 }}>
<Paper sx={{ padding: 5, height: '800px' }}>
<DataGrid
rows={posts}
columns={columns}
pageSize={10}
autoHeight
rowsPerPageOptions={[10]}
disableSelectionOnClick
disableColumnMenu
disableColumnSelector
components={{
LoadingOverlay: LoadingSkeleton,
}}
loading={loading}
/>
</Paper>
</Card>
</Container>
);
};
export default Home;
You should use a unique id for each item.您应该为每个项目使用唯一的 ID。 In your code
key="x.id"
, "x.id"
is just a string, which means it's the same for all items, that's incorrect在您的代码
key="x.id"
, "x.id"
只是一个字符串,这意味着它对所有项目都是相同的,这是不正确的
If you have unique ids for each item, use them.如果每个项目都有唯一的 ID,请使用它们。 Otherwise, you may use indexes as keys:
否则,您可以使用索引作为键:
{[...Array(10)].map((x, index) => (
<Skeleton variant="rectangular" sx={{ my: 4, mx: 1 }} key={index} />
))}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.