【发布时间】:2021-09-02 22:57:57
【问题描述】:
我在 Contentful 上的每篇文章都有一些与之相关的“类别”。例如,一篇帖子可能包含:
major: "HCD"
year: "1st Year"
tools: ["R", "Python", "Wordpress"]
这些只是名为major、year 等的字段,具有这些值,但它们被视为单独的类别。
在网站上,它们显示为:
我正在尝试为每个类别创建一个页面。例如,如果用户点击Photoshop,他们应该被带到一个页面tags/photoshop,并且所有包含该标签的帖子都应该被列出。
幸运的是,我找到了this guide 来帮我做这件事。但是,该指南不适用于内容数据,因此我在如何执行此操作时遇到了一些麻烦。我已经创建了tagsTemplate.jsx,但我一直在创建实际页面。
例如,这就是我尝试为tools 创建页面时所做的:
我的gatsby-node.js 文件如下所示:
const path = require(`path`)
const _ = require('lodash');
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions
const typeDefs = `
type contentfulPortfolioDescriptionTextNode implements Node {
description: String
major: String
author: String
tools: [String]
files: [ContentfulAsset]
contact: String
}
type ContentfulPortfolio implements Node {
description: contentfulPortfolioDescriptionTextNode
gallery: [ContentfulAsset]
id: ID!
name: String!
related: [ContentfulPortfolio]
slug: String!
major: String!
files: [ContentfulAsset]
author: String!
tools: [String]!
year: String!
thumbnail: ContentfulAsset
url: String
contact: String
}
`
createTypes(typeDefs)
}
exports.createPages = ({ graphql, actions }) => {
const { createPage } = actions
return new Promise((resolve, reject) => {
graphql(`
{
portfolio: allContentfulPortfolio {
nodes {
slug
tools
}
}
}
`).then(({ errors, data }) => {
if (errors) {
reject(errors)
}
if (data && data.portfolio) {
const component = path.resolve("./src/templates/portfolio-item.jsx")
data.portfolio.nodes.map(({ slug }) => {
createPage({
path: `/${slug}`,
component,
context: { slug },
})
})
}
const tools = data.portfolio.nodes.tools;
const tagTemplate = path.resolve(`src/templates/tagsTemplate.js`);
let tags = [];
// Iterate through each post, putting all found tags into `tags`
tags = tags.concat(tools);
// Eliminate duplicate tags
tags = _.uniq(tags);
// Make tag pages
tags.forEach(tag => {
createPage({
path: `/tags/${_.kebabCase(tag)}/`,
component: tagTemplate,
context: {
tag
},
});
});
console.log("Created Pages For" + tags)
resolve()
})
})
}
我的tagsTemplate 现在很小,因为我不知道如何查询数据:
import React from 'react';
import Layout from "../layouts/Layout"
const Tags = ({ data }) => {
return (
<Layout>
<div>Tags</div>
</Layout>
);
};
export default Tags;
问题:当我访问我知道存在的标签之一(如photoshop)的页面时,我得到一个 404。为什么没有创建这些页面?
我做错了什么,我该如何解决?这如何概括为我的三个“类别”?
【问题讨论】:
-
你能调试你的
tags数组吗? -
@FerranBuireu 我该怎么做?我试过
console.log(tags),但显示为undefined。这是在进行构建时。之后我不知道如何调试单个变量。 -
那么你不能从
undefined变量创建页面。tools里面有什么? -
@FerranBuireu,对于每个帖子,工具都是一个字符串数组,例如
["R", "Python", "Wordpress"]我的帖子顶部包含一个示例。 -
您的代码看起来不错,因为
tags应该用tools填充。输出是什么:tags.forEach(tag => {console.log(tag);createPage({path:`/tags/${_.kebabCase(tag)}/`,component: tagTemplate,context: {tag},});
标签: reactjs gatsby contentful