如何在Gatsby中从单个json文件创建多个页面 [英] How to create multiple pages from single json files in Gatsby

查看:102
本文介绍了如何在Gatsby中从单个json文件创建多个页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是node.js的新手,会做出反应,但我喜欢gatsby.js.我已经按照我可以找到的所有教程进行了学习,它是一个很棒的工具.

I am new to node.js and react but I love gatsby.js. I have followed all the tutorials that I can find and it's such a great tool.

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

However one of the main reasons why I want to use it is I have a file json with 1000 different records in and I would like to generate a new page for each record.

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

I believe I have come to the conclusion that I need to learn more about the gatsby-node.js file and am aware of the following resource but are there any tutorials or other examples on this topic that maybe a little easier to follow:

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

推荐答案

您所引用的示例应该已经为您提供了一个好主意.基本概念是导入JSON文件,对其进行循环并为JSON源中的每个项目运行createPage.因此,给出了一个示例源文件,例如:

The example you were referring to should already give you a good idea. The basic concept is to import the JSON file, loop over it and run createPage for each of the items in your JSON source. So given an example source file like:

pages.json

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

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

You can then use the Node API to create pages for each:

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
      }
    });
  });
};

这篇关于如何在Gatsby中从单个json文件创建多个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆