如何在数组map中根据mainImage是否为null显示/隐藏Image元素?
解决方案
要解决Cannot read properties of null (reading 'url')错误,并实现根据mainImage是否为null来显示/隐藏图片元素,只需给图片容器添加条件渲染逻辑即可:
修改后的完整代码
return ( <Container maxWidth="desktop"> <Typography variant="h1" sx={{ mb: 10 }}> Blog </Typography> <Stack gap={5} useFlexGap> {articles.map((article: Article) => ( <Box key={article._id} sx={{ display: "flex", gap: 3 }}> {/* 仅当mainImage不为null时渲染图片容器 */} {article.mainImage && ( <Box sx={{ position: "relative", aspectRatio: "16/9", flexShrink: 0, width: "30%", }} > <NextImage src={article.mainImage.url} alt={article.title} placeholder="blur" blurDataURL={ article.mainImage?.metadata?.lqip?.toString() ?? "" } fill style={{ objectFit: "cover", }} /> </Box> )} <Box> <Typography variant="h2" sx={{ mb: 2 }}> <Link href={`/blog/${article.slug}`} component={NextLink} underline="hover" > {article.title} </Link> </Typography> <Typography variant="body2" sx={{ mb: 2 }}> By: {article.author} </Typography> <Typography variant="body2">{article.excerpt}</Typography> </Box> </Box> ))} </Stack> </Container> );
关键改动说明
- 使用
{article.mainImage && (...)}包裹图片容器:当mainImage为null时,该表达式返回false,不渲染整个图片区域;当mainImage存在时,才会渲染图片组件,从根源避免访问null属性的错误。 - 保留原有的
blurDataURL可选链逻辑:即使mainImage存在但metadata或lqip缺失,也不会报错,而是返回空字符串作为兜底。
内容的提问来源于stack exchange,提问作者Rey
相关产品推荐
相关产品推荐

