【问题标题】:Loading content from a static JSON Next JS从静态 JSON Next JS 加载内容
【发布时间】:2021-10-23 18:23:39
【问题描述】:

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

{
  "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

【问题讨论】:

    标签: next.js components react-props


    【解决方案1】:

    这里不需要 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 />
        </>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-19
      • 2012-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多