我正在使用React App。对于样式,我使用的是Material-UI库。
我从一个开放的API中获取数据,并将数据传递到子组件中,并将其呈现给子组件。我使用了Material-UI网格,并希望在一行中显示三张卡片。
我的应用程序运行正常,但它显示相同的数据三次。我知道此问题来自Material-UI,但不知道如何修复它。
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
import Typography from "@material-ui/core/Typography";
import Grid from "@material-ui/core/Grid";
import moment from "moment";
const useStyles = makeStyles(theme => ({
gridRoot: {
flexGrow: 1
},
root: {
display: "flex",
flexWrap: "wrap",
"& > *": {
margin: theme.spacing(1),
width: theme.spacing(16),
height: theme.spacing(16)
}
},
paper: {
width: "390px",
height: "200px",
textAlign: "center",
padding: "30px",
borderRadius: "25px"
},
subText: {
fontWeight: "fontWeightMedium",
paddingBottom: "3px",
fontSize: "18px",
fontFamily: "Roboto Condensed"
}
}));
function HeroCard({ districts, source, date }) {
const [spacing, setSpacing] = React.useState(2);
const classes = useStyles();
return (
<React.Fragment>
<Grid container className={classes.gridRoot} spacing={2}>
<Grid item xs={12}>
<Grid container justify="center" spacing={spacing}>
{[0, 1, 3].map(value => ( //PROBLEM IS COMING FROM HERE.
<Grid key={value} item>
<Paper className={classes.paper}>
<Typography className={classes.subText}>
Health care district: {districts ? districts : "Unknown"}
</Typography>
<Typography className={classes.subText}>
Infection source of country: {source ? source : "Unknown"}
</Typography>
<Typography className={classes.subText}>
Date of infected: {moment(date).format("LLLL")}
</Typography>
</Paper>
</Grid>
))}
</Grid>
</Grid>
</Grid>
</React.Fragment>
);
}
export default HeroCard;
我不认为问题出在材质界面上
map方法正在遍历您从API调用获得的JSON对象,但是,在代码中,您需要根据要接收的JSON对象使用value.id或value.districts。映射(值=>(
<Grid key={value.id} item>
<Paper className={classes.paper}>
<Typography className={classes.subText}>
Health care district: {value.districts ? value.districts : "Unknown"}
</Typography>
</Grid>
))