【发布时间】:2021-04-08 08:11:01
【问题描述】:
我使用 CardMedia 显示图像,当我转到主页时,它不显示图像并且有一些错误。当我单击一些链接并在浏览器中使用“返回”按钮时,图像会返回。
我使用getInitialProps() 在 Home 组件中获取图像 url 并作为属性传递给子(目录)组件。
我认为图像 url 会在 Home 组件中接收,然后 CardMedia 将从 Home 组件接收的图像呈现为道具。 有什么想法吗?
export default function Home({ categories }) {
return (
<div>
<Header categories={ categories}/>
<Carousel />
<Catalog categories={ categories}/>
<Footer/>
</div>
)
}
Home.getInitialProps = async () => {
const response = await fetch('http://localhost:1337/categories/')
const categories = await response.json();
return {
categories:categories
}
}
export default function Catalog(props) {
const classes = useStyles();
const cards = props.categories
const server = 'http://localhost:1337'
console.log(cards)
return (
<React.Fragment>
<CssBaseline />
<main>
{/* Hero unit */}
<div className={classes.heroContent}>
<Container maxWidth="sm">
<Typography component="h1" variant="h2" align="center" color="textPrimary" gutterBottom>
Album layout
</Typography>
<Typography variant="h5" align="center" color="textSecondary" paragraph>
Something short and leading about the collection below—its contents, the creator, etc.
Make it short and sweet, but not too short so folks don't simply skip over it
entirely.
</Typography>
</Container>
</div>
<Container className={classes.cardGrid} maxWidth="md">
{/* End hero unit */}
<Grid container spacing={4}>
{cards.map((card) => (
<Link as={`/products/${card.category}`} href='/products/[bathroom]' key={card.id}>
<Grid item key={card.category} xs={12} sm={6} md={4} >
<Card className={classes.card}>
<CardMedia
className={classes.cardMedia}
image={server+ card.img.url}
category={card.category}
/>
<CardContent className={classes.cardContent}>
<Typography gutterBottom variant="h5" component="h2">
{card.category}
</Typography>
<Typography>
Product description.
</Typography>
</CardContent>
</Card>
</Grid>
</Link>
))}
</Grid>
</Container>
</main>
{/* Footer */}
{/* End footer */}
</React.Fragment>
);
}
【问题讨论】:
-
嗨 @hei o 认为您缺少 src 组件和 CardMedia documentation 建议使用的高度。
-
@VitDev 您好,Home 组件是 src 组件。该图像曾经使用“返回”按钮,不知道为什么它在初始阶段不渲染
标签: reactjs material-ui