【问题标题】:React.js error :TypeError: Cannot read property 'map' of undefinedReact.js 错误:TypeError:无法读取未定义的属性“地图”
【发布时间】:2021-03-29 21:49:15
【问题描述】:

目前正在尝试根据本教程制作一个 MERN Stack 网络应用程序: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 | }

【问题讨论】:

  • 我猜这意味着 post.tags 未定义?您是否尝试过将“post”变量打印到控制台,或在调试器中检查它?
  • 基本上就是说,你的post.tagsundefined。尝试检查是否正确获取数据或检查您的 post 是否具有属性 - tags
  • post.tags && post.tags.map((tag) => #${tag} - 添加空检查

标签: javascript node.js reactjs mongodb mern


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多