【问题标题】:Error serializing props returned from `getStaticProps` in "/"序列化从“/”中的“getStaticProps”返回的道具时出错
【发布时间】:2021-12-25 22:30:29
【问题描述】:

我正在尝试使用 Strapi+ graphql 构建一个 NextJs 博客网站。但是按照官方strapi视频源给出的步骤后,我在home.jsx文件中遇到了这个问题......

Error: Error serializing props returned from `getStaticProps` in "/".
Reason: Props must be returned as a plain object from getStaticProps: `{ props: { ... } }` (received: `[object Undefined]`).

这是 Home.jsx 页面代码:

import { Fragment } from "react";
import HomePage from "./home/home";
import { ApolloClient, InMemoryCache, gql } from "@apollo/client";


export async function getStaticProps() {
  const client = new ApolloClient({
    url: "http:/localhost:1337/graphql",
    cache: new InMemoryCache(),
  });

  const GET_BLOGS = gql`
    query getBlogs {
      blogs {
        id: string
        title: string
      }
    }
  `;
  let getData = client.query({ query: GET_BLOGS });
  console.log("" + getData);

  return { props: getData.blogs };
}

export default function Home({ blogs }) {
  if (blogs) return console.log(blogs);
  return (
    <Fragment>
      <HomePage />
    </Fragment>
  );
}

可能是 next 和 Strapi package.json 文件的依赖问题,所以这里是两者的依赖关系:

Nextjs package.json 依赖项-

  "dependencies": {
    "@apollo/client": "^3.4.17",
    "axios": "^0.24.0",
    "graphql": "^16.0.1",
    "next": "12.0.2",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "react-toastify": "^8.1.0"
  },

Strapi 项目依赖:

"dependencies": {
    "knex": "0.21.18",
    "sqlite3": "5.0.0",
    "strapi": "3.6.8",
    "strapi-admin": "3.6.8",
    "strapi-connector-bookshelf": "3.6.8",
    "strapi-plugin-content-manager": "3.6.8",
    "strapi-plugin-content-type-builder": "3.6.8",
    "strapi-plugin-email": "3.6.8",
    "strapi-plugin-graphql": "3.6.8",
    "strapi-plugin-i18n": "3.6.8",
    "strapi-plugin-upload": "3.6.8",
    "strapi-plugin-users-permissions": "3.6.8",
    "strapi-utils": "3.6.8"
  },
"engines": {
    "node": ">=10.16.0 <=14.x.x",
    "npm": "^6.0.0"
  },

【问题讨论】:

  • 修正错字,http:/localhost:1337/graphqlhttp://...
  • console.log(getData) 在终端输出什么?

标签: graphql next.js apollo-client strapi graphql-js


【解决方案1】:

您可以根据您的情况检查以下选项,看看它是否有效。

1. Try to do finalData = getData.json(), and then destruce it like finalData.blogs()
2. Const finalData = JSON.Stringify(getData); and then use final data.

网络调用响应需要在jsx中序列化,应用以上两种情况即可解决问题

【讨论】:

  • 我已经试过了。但它没有工作保存问题发生。
  • 你可以打印从graphql返回的数据吗?
  • 是的,实际上,Axios 在幕后做得更好,上面的查询在 Graphql localhost:1337/graphql 中运行良好。但无论我尝试 json。 stringify json.parse 或 axios 都显示相同的错误。我从头开始重建整个项目,感觉可能是 next、graphql 或 stripi 的版本问题?但我是strapi的新手,所以不知道如何解决。
  • 这里是 graphql 中的查询输出:
  • { "data": { "blogs": [ { "id": "1", "title": "M1 vs M1 Pro 和 M1 Max" }, { "id": "2 ", "title": "M1 vs 英特尔" } ] } }
猜你喜欢
  • 2021-08-06
  • 2023-03-06
  • 1970-01-01
  • 2021-04-23
  • 2021-06-22
  • 2021-08-25
  • 2021-06-19
  • 2020-12-05
  • 2021-03-22
相关资源
最近更新 更多