[英]Next.js Error serializing `.res` returned from `getServerSideProps`
[英]Error serializing - using getServerSideProps in next.js
显示错误
错误:序列化从“/blog”中的
getServerSideProps
返回的.myBlogs
时出错。```
当我试图控制数据时! 当我通过useEffect()
获取数据时,一切进展顺利,但现在使用getServerSideProps
获取数据时会引发上述错误!
代码:
import React, { useEffect, useState } from 'react'
import styles from '../styles/Blog.module.css'
import Link from 'next/link'
import Navbar from '../components/Navbar'
const blog = (props) => {
console.log(props)
const [blogs, setblogs] = useState([]);
// useEffect(() => {
// }, [])
return <div>
<Navbar />
<main className={styles.main}>
<h2 className={styles.heading}>
Latest Blogs :)
{/* Get started by editing{' '}
<code className={styles.code}>pages/index.js</code> */}
</h2>
<div className={styles.neat}>
{blogs.map((blogitem) => {
return <div className={styles.grid} key={blogitem.slug} >
<Link href={`/blogpost/${blogitem.slug}`} >
<a className={styles.card}>
<h2>{blogitem.title} →</h2>
<p>{blogitem.content.substr(0, 100)}...</p>
</a>
</Link>
</div>
})}
</div>
</main>
</div>
}
export async function getServerSideProps(context) {
let data = await fetch('http://localhost:3000/api/blogs');
let myBlogs = await data.json();
return {
props: {myBlogs}, // will be passed to the page component as myBlogs
}
}
export default blog
正如@Bravo 建议的那样,您应该在getServerSideProps
回调中await
data.json()
调用。
此外,您应该解构props
对象以接收加载的blogs
并显示它们。
最后,在React
中将组件名称大写是一种很好的做法:
const Blog = ({ blogs }) => {
return <div>
<Navbar />
<main className={styles.main}>
<h2 className={styles.heading}>
Latest Blogs :)
{/* Get started by editing{' '}
<code className={styles.code}>pages/index.js</code> */}
</h2>
<div className={styles.neat}>
{blogs.map((blogitem) => {
return <div className={styles.grid} key={blogitem.slug} >
<Link href={`/blogpost/${blogitem.slug}`} >
<a className={styles.card}>
<h2>{blogitem.title} →</h2>
<p>{blogitem.content.substr(0, 100)}...</p>
</a>
</Link>
</div>
})}
</div>
</main>
</div>
}
export async function getServerSideProps(context) {
let data = await fetch('http://localhost:3000/api/blogs');
let myBlogs = await data.json();
return {
props: { blogs: myBlogs },
}
}
export default Blog
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.