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
我该怎么办?我不知道它为什么会出现,因为,最近我用了类似的方法,但现在它抛出这样的错误,一切都很好!请帮我把错误弄出来!
这是错误的照片:
发布于 2022-05-12 11:58:14
像这样改变getServerSideProps,返回一些有意义的东西,它实际上代表了您的数据,而不是像data这样的关键字,这很让人困惑。通过返回{ 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只在数组上工作。
发布于 2022-05-12 12:00:34
按照访问博客的方式,您需要将博客作为一个关键:
let blogs = await totalBlogs.json();
return {
props: { data : { blogs } }, // will be passed to the page component as props
}或者你可以这么做:
const [blogs, setblogs] = useState(props);发布于 2022-05-12 12:22:19
您所得到的错误意味着blogs对象是未定义的,因此,blogs.map也是未定义的,在被调用时引发错误。
尝试使用可选链接:
{blogs?.map((blogitem) => {
...https://stackoverflow.com/questions/72215061
复制相似问题