簡體   English   中英

序列化錯誤 - 在 next.js 中使用 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} &rarr;</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} &rarr;</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.

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