How to create multiple pages from single json files in Gatsby

China☆狼群 提交于 2019-11-29 01:36:11

问题


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.

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.

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


回答1:


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"
}]

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


来源:https://stackoverflow.com/questions/48652257/how-to-create-multiple-pages-from-single-json-files-in-gatsby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!