import Head from 'next/head'
import { useState } from 'react'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
const Home = (props) => {
const [blogs, setblogs] = useState(props.data);
return <div className={styles.container}>
<Head>
<title>BlogsWap</title>
<meta name="description" content="New App" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1 className={styles.title}>
Welcome to <a href="https://nextjs.org">BlogsWap!</a>
</h1>
<p className={styles.description}>
An all time blog for coders!
</p>
{blogs.map((blogitem) => {
return <div className={styles.grid}>
<a href="https://nextjs.org/docs" className={styles.card}>
<h2>{blogitem.title} →</h2>
<p>{blogitem.content}</p>
</a>
</div>
})}
</main>
<footer className={styles.footer}>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
© BlogsWap
<span className={styles.logo}>
</span>
</a>
</footer>
</div>
}
export async function getServerSideProps(context) {
let totalBlogs = await fetch('http://localhost:3000/api/blogs');
// console.log(totalBlogs)
let data = await totalBlogs.json();
return {
props: { data }, // will be passed to the page component as props
}
}
export default Home
我收到如下錯誤:
TypeError: blogs.map is not a function
我該怎么辦?我不知道它為什么會出現,因為最近我使用了類似的方法,但現在一切都很好,它拋出了這樣的錯誤!請幫助我解決錯誤!
這是錯誤的照片:(
發生錯誤的照片
uj5u.com熱心網友回復:
編輯:更改getServerSideProps(context)為:
export const getServerSideProps = async (req, res) => {
try {
const blogs = await fetch('http://localhost:3000/api/blogs');
res.status(200).json(blogs);
} catch (error) {
res.status(404).json({ message: error.message });
}
}
試試這個(blogs &&在地圖之前添加):
//This checks if blogs is defined before doing the map on it
{blogs && blogs.map((blogitem) => {
return <div className={styles.grid}>
<a href="https://nextjs.org/docs" className={styles.card}>
<h2>{blogitem.title} →</h2>
<p>{blogitem.content}</p>
</a>
</div>
})}
uj5u.com熱心網友回復:
您收到的錯誤意味著該blogs物件未定義,因此blogs.map也未定義,在呼叫時會引發錯誤。
嘗試使用可選鏈接:
{blogs?.map((blogitem) => {
...
uj5u.com熱心網友回復:
您訪問博客的方式,您需要將博客作為鍵傳遞:
let blogs = await totalBlogs.json();
return {
props: { data : { blogs } }, // will be passed to the page component as props
}
或者你可以這樣做:
const [blogs, setblogs] = useState(props);
uj5u.com熱心網友回復:
像這樣改變getServerSideProps,回傳一些有意義的東西,它實際上代表你的資料,而不是像資料這樣的關鍵字,這很令人困惑。通過回傳{ props: { blogData } },組件將blogData作為道具接收。
let blogData = await totalBlogs.json();
return {
props: { blogData }, // will be passed to the page component as props
}
然后你需要改變你傳遞道具的組件的輸入,現在是blogData. 注意這里的變化,這里使用了解構。
const Home = ({ blogData }) =>
const [blogs, setblogs] = useState(blogData);
最后在 jsx 中也做空檢查以安全訪問物件
{blogs && ....
<map goes here>
}
或者
{blogs ?
<map goes here>
:
else show a loader here
我也希望blogData是一個陣列型別,如果不使用將它轉換為陣列
Array.from(blogData)
因為.map僅適用于陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/472685.html
