无法从 Strapi API 获取数据到 next.js 前端

问题描述

我尝试过使用 Strapi 和 next.js 来制作博客网站。这是前端代码的next.js

import Head from 'next/head'
import styles from '../styles/Home.module.css'

export default function Home({ posts }) {

  return (
    <div>
      {posts && 
      
      posts.map((posts) => (

        <div key={post.id}>
            <h2>{posts.title}</h2>
        </div>
      ))}
    </div>
  );
}



export async function getstaticProps() {

  //get post from our API

  const res = await fetch("http://localhost:1337/posts");
  const posts = await res.json();

  return {
    props: { posts },};

}

这里是 Strapi API Json 数据

[
{
"id": 1,"title": "Hello Everyone","slug": "hello-everyone","content": "Hello All.","users_permissions_user": {
"id": 4,"username": "tanha","email": "tanha@test.com","provider": "local","confirmed": true,"blocked": false,"role": 1,"created_at": "2021-03-12T06:02:44.726Z","updated_at": "2021-03-12T06:03:54.507Z"
},"published_at": "2021-03-11T19:37:02.117Z","created_at": "2021-03-11T19:36:46.663Z","updated_at": "2021-03-12T11:48:57.275Z"
}
]

这里有什么问题?我尝试过,但在这里没有发现任何错误。但是无法获取数据前端显示

解决方法

如果您使用 Next.js 并希望充分利用静态渲染,我建议您尽可能避免使用 getStaticProps。

这是一个使用纯组件且完全没有道具的工作示例。

const Home = () => {
  const [posts,setPosts] = React.useState(null);

  const getPosts = async() => {
    const res = await fetch("http://localhost:1337/posts");
    const json = await res.json();
    setPosts(json);
  }

  if(!posts){
    getPosts();
  }

  return (
    <div>
      {posts ? posts.map((post) => (
        <div key={post.title}>
            <h2>{post.title}</h2>
        </div>
      )) : (
        <div>Loading...</div>
      )}
    </div>
  )
}

export default Home;
,

getstaticProps 应该是不同的情况 -> getStaticProps,除了您的代码看起来不错。