【问题标题】:How to differentiate some content when pages are created programmatically in Gatsby JS在 Gatsby JS 中以编程方式创建页面时如何区分某些内容
【发布时间】:2019-12-23 01:17:43
【问题描述】:

我正在使用 Gatsby 构建一个网站,到目前为止,我发现以编程方式创建页面是一个非常方便的功能。您可以拥有一个类别模板,并让 gatsby-node 非常轻松地为每个内容类别创建页面。 但是,向同一模板添加差异化内容的推荐方法是什么?

现在我正在使用三元运算符来检查它是哪个类别,并根据该精确类别添加特定内容(需要相应区分的一些内容示例:类别介绍标题、SEO 标题和 SEO 描述基于 Helmet 的 SEO 组件)

在 categoryTemplate.js 中

const booksTitle = "Quote on books"
const songsTitle = "Quote on songs"
const travelsTitle = "Quote on travels"
const booksSeoTitle = "Books Title for SEO"
...

               <CategoryIntro
                    title={<>
                        {category === "books"
                        ? booksTitle
                        : category === "songs"
                        ? songsTitle
                        : category === "travels"
                        ? travelsTitle
                        : null
                        }
                    </>}
              />

这种方法确实有效,但我想知道是否有更方便的做法可以使用?我应该在其他地方以 json 格式存储有关类别的信息,而不是在模板文件中声明它们吗?

非常感谢。

【问题讨论】:

  • 我会在模板外部分配title,作为let title = ''switch(category) { ... },然后在模板内部分配title={title}

标签: javascript reactjs graphql gatsby


【解决方案1】:

我认为您建议的将这些信息存储在其他地方的方法会使代码更简洁且更易于维护。模板组件应仅为预期的通用模板。你不应该把它和内容混在一起。

categories.js 文件怎么样?

export const categories = {
  book: {
    title: "Quote on books",
    seoTitle: "",
  },
  songs: {
    title: "Quote on songs",
    seoTitle: "",
  },
}

在你的模板文件中导入你的categories.js,让它通过一个道具决定选择哪个类别:

import { categories } from "./categories.js"

// This function returns your mediaType object
function getObject(obj, mediaType) {
  return obj[mediaType];
}

function MediaTemplate({ mediaType }) {

  const category = getObject(mediaType);
  // See this answer for how to access the object key dynamically: https://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-by-name-as-string

  console.log("category:");
  console.log(category);

  // It is only one amazing line now!
  return (
    <CategoryIntro title={category.title} />
  );
}

【讨论】:

  • 您好,非常感谢!我喜欢这种方法,但我认为我没有以正确的方式访问对象键,因为我收到错误“无法读取未定义的属性”。关于可能是什么问题的任何线索?我检查了您链接的答案,但即使看起来我正在按照那里的建议进行操作,它似乎也不起作用。
  • @Giulia 我自己测试了它并编辑了我的答案以获得正确的解决方案。 =)
  • 非常感谢!!它工作得很好:)(请原谅迟到的回复,远离电脑)
猜你喜欢
  • 2018-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-16
  • 2020-04-29
  • 1970-01-01
  • 2021-06-09
  • 2014-02-13
相关资源
最近更新 更多