簡體   English   中英

React.js 錯誤:TypeError:無法讀取未定義的屬性“地圖”

[英]React.js error :TypeError: Cannot read property 'map' of undefined

目前正在嘗試從本教程中制作 MERN 堆棧 web 應用程序: https://youtu.be/aibtHnbeuio所以我在堆棧上也很新,不知道如何解決這個問題......幫助 plz

類型錯誤:無法讀取未定義帖子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引起的,如果是這種情況,那么最初post的值將保持undefined ,您將看到此錯誤。

使用 null 傳播或條件渲染來避免此錯誤:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM