从 Next js 前端从 Strapi API 请求的数据未显示数据

Data requested from Strapi API from Next js Frontend not showing data

你好,我试图制作一个 TikTok 克隆,所以我 运行 遇到了一个问题,我无法在我的 nextjs 前端显示来自我的 strapi 后端的数据,并通知你我允许 public请求下面的 API 代码

import axios from "axios";

const Post = ({ posts, error }) => {
  if (error) {
    return <div>An error occured: {error.message}</div>;
  }
  return (
    <ul>
      {posts.length > 0 &&
        posts.map((post) => <li key={post.id}>{post.title}</li>)}
    </ul>
  );
};

Post.getInitialProps = async (ctx) => {
  try {
    const res = await axios.get("http://localhost:1337/api/posts");
    const posts = res.data;
    return { posts };
  } catch (error) {
    return { error };
  }
};

export default Post;

这是解决问题后更正的代码

import axios from "axios";
import React, { useRef, useState } from "react";
const Post = ({ posts, error }) => {
  if (error) {
    return <div>An error occured: {error.message}</div>;
  }
  return (
       <ul>
      {posts.length > 0 &&
        posts?.map((post) => <li key={post.id}>{post.attributes.title}</li>)}
    </ul>
  );
};

Post.getInitialProps = async (ctx) => {
  try {
    const res = await axios.get("http://localhost:1337/api/posts");
    const posts = res.data.data;
    return { posts };
  } catch (error) {
    return { error };
  }
};

export default Post;