我在/pages/api/data中放置了静态JSON的Next JS项目。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>
))}; }
</>
);
但是我得到一个Type: Undefined错误,我很确定这不是函数应该看起来的样子。
另外,如果我想导出它作为一个组件,我可以在我的index.js中使用,我必须命名导出默认函数吗?回购链接在这里:https://github.com/DoctorSte/remoteOS
这里不需要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 />
</>
);
}
- 在我的例子中,我像下面的例子一样导入它
模拟/database.json
[
{
"id": 1,
"name": {
"first": "John",
"last": "Smith"
},
"total": 2795.95,
"status": "On Hold",
"method": "PayPal",
"date": "15 Minutes ago"
},
...
]
组件/RecentOrders.tsx
import data from "@/mock/database.json";
const RecentOrders = () => {
return <div>{JSON.stringify(data, null, 2)}</div>;
};
export default RecentOrders;