json - 如何在 Gatsby 中从单个 json 文件创建多个页面

标签 json node.js reactjs graphql gatsby

我是 node.js 的新手,但我喜欢 gatsby.js。我已经按照我能找到的所有教程进行操作,这是一个很棒的工具。

然而,我想使用它的主要原因之一是我有一个包含 1000 条不同记录的文件 json,我想为每条记录生成一个新页面。

我相信我已经得出结论,我需要了解有关 gatsby-node.js 文件的更多信息,并且了解以下资源,但是是否有任何关于此主题的教程或其他示例可能更容易理解:

https://www.gatsbyjs.org/docs/creating-and-modifying-pages/#creating-pages-in-gatsby-nodejs

最佳答案

你提到的例子应该已经给了你一个好主意。基本概念是导入 JSON 文件,遍历它并为 JSON 源中的每个项目运行 createPage。所以给出一个示例源文件,如:

pages.json

[{
  "page": "name-1"
}, {
  "page": "name-2"
}]

然后您可以使用 Node API 为每个页面创建页面:

gatsby-node.js

const path = require('path');
const data = require('./pages.json');

exports.createPages = ({ boundActionCreators }) => {
  const { createPage } = boundActionCreators;

  // Your component that should be rendered for every item in JSON.
  const template = path.resolve(`src/template.js`);

  // Create pages for each JSON entry.
  data.forEach(({ page }) => {
    const path = page;

    createPage({
      path,
      component: template,

      // Send additional data to page from JSON (or query inside template)
      context: {
        path
      }
    });
  });
};

关于json - 如何在 Gatsby 中从单个 json 文件创建多个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48652257/

相关文章:

node.js - MongoDB:如何在客户端解析DBRef?

reactjs - 处理 Typescript 中的可选字段

javascript - 举例来说,Material UI 中的 `getOptionSelected` 和 `getOptionLabel` 是什么?

javascript - 错误!缺少脚本 : Start when deploying to heroku

java - 处理来自数据库的响应并将其传递给新 Activity

python - Django 模型不可 JSON 序列化

node.js - NPM 预安装脚本

python - 根据条件更改多个文件的名称

node.js - 断言错误: expected stub to have been called with arguments 201

javascript - ReactJS + 终极版 : How to wait until dispatch has been completed before moving onto next step?