簡體   English   中英

無法讀取未定義的屬性(讀取“地圖”)反應 JS

[英]Cannot read properties of undefined (reading 'map') react JS

我正在嘗試在 VS Code 中使用 ReactJS 和 NextJS 創建一個博客,但沒有任何錯誤,但是當我運行它時,它會在瀏覽器中顯示:“TypeError: Cannot read properties of undefined (reading 'map')”

所以這是代碼

 import React, { useState, useEffect } from 'react'; import Image from 'next/image'; import moment from 'moment'; import Link from 'next/link'; import { getSimilarPosts, getRecentPosts } from '../services'; const PostWidget = ({ categories, slug }) => { const [relatedPosts, setRelatedPosts] = useState([]); useEffect(() => { if (slug) { getSimilarPosts(categories, slug).then((result) => { setRelatedPosts(result); }); } else { getRecentPosts().then((result) => { setRelatedPosts(result); }); } }, [slug]) console.log(relatedPosts) return ( <div className="bg-white shadow-lg rounded-lg p-8 pb-12 mb-8"> <h3 className="text-xl mb-8 font-semibold border-b pb-4">{slug ? 'Related Posts' : 'Recent Posts'}</h3> {relatedPosts.map((post) => ( <div key={post.title} className="flex items-center w-full mb-4"> <div className="w-16 flex-none"> <img alt={post.title} height="60px" width="60px" unoptimized className="align-middle rounded-full" src={post.featuredImage.url} /> </div> <div className="flex-grow ml-4"> <p className="text-gray-500 font-xs">{moment(post.createdAt).format('MMM DD, YYYY')}</p> <Link href={`/post/${post.slug}`} className="text-md" key={index}>{post.title}</Link> </div> </div> ))} </div> ); }; export default PostWidget;

這就是錯誤所在。

{relatedPosts.map((post) =>

使用? 在這段代碼中制作:

{relatedPosts?.map((post) =>

在渲染地圖之前檢查relatedPosts是否有數據。 如果不起作用,請分享getSimilarPosts、getRecentPosts

{
   relatedPosts && 
   relatedPosts.length > 0 &&
   relatedPosts.map((post) => (
      ...
   ))
}

暫無
暫無

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

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