从静态JSON加载内容Next JS

at0kjp5o  于 2023-03-18  发布在  其他
关注(0)|答案(2)|浏览(435)

我有一个Next JS项目,静态JSON放在/pages/api/data. json中,如下所示:

{
 "Card": [
   { "title": "Title 1", "content": "Content 1" },
   { "title": "Title 2", "content": "Content 2" },
   { "title": "Title 3", "content": "Content 3" }
 ]
}

我尝试从JSON中获取内容,以便在几个部分中加载,如下所示:

import { Card } from "../api/data";

export const getStaticProps = async () => {
  return {
    props: { cardData: Card },
  };
};

export default ({ cardData }) => (
  <>
    const card = cardData.title; console.log(cardData);
    { {cardData.map((cardData) => (
      <div>
        <h3>{cardData.title}</h3>
        <p>{cardData.content}</p>
      </div>
    ))}; }
  </>
);

但我得到了一个类型:未定义的错误,我很确定函数不应该是这样的。
另外,如果我想把它导出为一个可以在index.js中使用的组件,我是否必须将导出的默认函数命名为?repo link here:https://github.com/DoctorSte/remoteOS

41zrol4v

41zrol4v1#

这里不需要getStaticProps,Webpack会在构建时为您绑定JSON。下面是contact.js页面的一个工作示例:

import "tailwindcss/tailwind.css";

import Footer from "./components/footer";
import Form from "./components/form";
import Navbar from "./components/Navbar";

import Cards from "./api/data.json"

export default function Contact() {
 
 console.log(Cards['Cards 1'][0].title); // Title 1

 return (
    <>
      <Navbar />
      <Form />
      <Footer />
    </>
  );
}
hi3rlvi2

hi3rlvi22#

  • 在我的例子中,我像下面的例子一样导入它

模拟/数据库. json

[
  {
    "id": 1,
    "name": {
      "first": "John",
      "last": "Smith"
    },
    "total": 2795.95,
    "status": "On Hold",
    "method": "PayPal",
    "date": "15 Minutes ago"
  },
  ...
]

组件/最近订单.tsx

import data from "@/mock/database.json";

const RecentOrders = () => {
  return <div>{JSON.stringify(data, null, 2)}</div>;
};

export default RecentOrders;

相关问题