[英]Is it nessesary to use getStaticProps with json import in Next.js?
I want to render static data that is coming from a JSON or typescript file and display it to the user.我想渲染来自 JSON 或打字稿文件的静态数据并将其显示给用户。 Do I have to use
getStaticProps
or can I simply import the data without getStaticProps
?我是否必须使用
getStaticProps
或者我可以在没有getStaticProps
的情况下简单地导入数据? It's not clear to me after reading the next documentation.阅读下一个文档后,我不清楚。
projects.tsx项目.tsx
const projects: [
{
id: "6853939";
name: "Project 01";
title: "Title 01 ";
previewImg: "/images/projectThumbnails/image01.jpg";
},
{
id: "6853939";
name: "Project 02";
title: "Title 02 ";
previewImg: "/images/projectThumbnails/image02.jpg";
}
];
export default projects;
names.json名称.json
{
"names": [
{ "name": "Full Name 01", "age": 34 },
{ "name": "Full Name 02", "age": 22 },
],
}
index.tsx索引.tsx
import projects from "../data/projects.tsx";
import names from "../data/names.json";
const IndexPage = () => {
return (
<>
<div>
{projects.map((i) => (
<div key={i.id}>{i.title}</div>
))}
</div>
<div>
{names.names.map((i) => (
<div key={i.name}>{i.name}</div>
))}
</div>
</>
);
};
It's totally up to you which approach you are going to use .您将使用哪种方法完全取决于您。
With getStaticProps
:使用
getStaticProps
:
server uses JSON
data to inject data and create cache服务器使用
JSON
数据注入数据并创建缓存
Without getStaticProps
:没有
getStaticProps
:
JSON file would be injected in client side , without being cached JSON文件将被注入客户端,而不被缓存
I prsonally recommend using getStaticProps
我个人建议使用
getStaticProps
Importing JSON in getStaticProps
:在
getStaticProps
中导入 JSON:
import yourJson from ('./somefile.json') export async function getStaticProps(context) { //use your json here return { props: {}, // will be passed to the page component as props } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.