首页 > 解决方案 > React.js 错误:TypeError:无法读取未定义的属性“地图”

问题描述

目前正在尝试从本教程制作一个 MERN Stack Web 应用程序:https : //youtu.be/aibtHnbeuio 所以我对堆栈也很陌生,不知道如何解决这个问题......请帮助

TypeError:无法读取未定义帖子 C:/Users/I/Desktop/memories-pr/client/src/components/Posts/Post/Post.js:27的属性“地图”

  24 |     </Button>
  25 | </div>
  26 | <div className={classes.details}>
> 27 |     <Typography variant="body2" color="textSecondary" component="h2">{post.tags.map((tag) => `#${tag} `)}</Typography>
     |   28 | </div>
  29 | <CardContent>
  30 |     <Typography className={classes.title}  variant="h5" gutterBottom > {post.message} </Typography>

(匿名函数)C:/Users/I/Desktop/memories-pr/client/src/actions/posts.js:8

 5 | try {
   6 |     const { data } = await api.fetchPosts();
   7 | 
>  8 |     dispatch({ type: 'FETCH_ALL', payload: data});
     | ^   9 | } catch (error) {
  10 |     console.log(error.message);
  11 | }

标签: javascriptnode.jsreactjsmongodbmern

解决方案


这可能是由post异步获取引起的,如果是这种情况,那么最初的值post将保持不变undefined,您将看到此错误。

使用空传播或条件渲染来避免此错误:

<Typography 
    variant="body2" 
    color="textSecondary"    
   component="h2">
     {post?.tags?.map((tag) => `#${tag} `)}
</Typography>

推荐阅读