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

编程入门 行业动态 更新时间:2024-10-26 16:30:28
本文介绍了如何从 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/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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-27 02:09:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/674135.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   页面   文件   Gatsby   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!