警告"列表中的每个子元素都应该有一个唯一的"键"支持# 39;即使有关键存在(React



我正在尝试使用map函数从JSON文件中获取数据,但我一直得到这个错误'列表中的每个孩子都应该有一个唯一的'键';尽管我设置了key={facts.id}。请问我怎样才能摆脱这个错误?其他的都很好。

import React from "react";
import ResponsiveAppBar from "./ResponsiveAppBar";
import Typography from "@mui/material/Typography";
import { styled } from "@mui/material/styles";
import Box from "@mui/material/Box";
import Paper from "@mui/material/Paper";
import Grid from "@mui/material/Grid";
import Facts from "../sources/facts.json";
import Data from "../sources/credits.json";
const Learn = () => {
const Item = styled(Paper)(({ theme }) => ({
backgroundColor: theme.palette.mode === "dark" ? "#1A2027" : "#fff",
...theme.typography.body2,
padding: theme.spacing(2),
textAlign: "center",
color: theme.palette.text.secondary,
}));
return (
<div>
<ResponsiveAppBar />
{Facts &&
Facts.map((fact) => {
return (
<Box sx={{ flexGrow: 1 }}  style={{
marginTop:50}}>
<Grid 
container
spacing={2}
elevation={9}
justifyContent="center"
style={{ margin: "auto" }}
>
<Grid item xs={8} >
<Item key={fact.id} >
<Typography
variant="h5"
gutterBottom
component="div"
style={{ fontWeight: 600 }}
>
{fact.id}. {fact.title}
</Typography>
<Typography variant="body1" gutterBottom>
{fact.content}
</Typography>
</Item>
</Grid>
</Grid>
<br />
<br />
</Box>
);
})}
</div>
);
};
export default Learn;

您应该将key赋值给您返回的第一个元素:

return (
<Box key={fact.id} sx={{ flexGrow: 1 }}  style={{
marginTop:50}}>

我通过向map函数参数添加索引,并设置键等于索引,使其工作。


Facts.map((fact, i) => {
return (
<Box sx={{ flexGrow: 1 }}  style={{
marginTop:50} key={i}>

最新更新