Gatsby调用createPage生成标签页时数据返回undefined问题求助
问题根源
你的代码核心问题出在标签页模板的数据读取逻辑,和GraphQL返回结果的结构不匹配:
- 模板中你已经通过
$tags参数过滤了仅查询单个标签对应的文章,返回的data.allMdx.group是仅含1个元素的数组,你直接读取数组的fieldValue属性必然返回undefined - 分组下的
nodes是文章数组,你没有遍历这个数组,直接读取nodes.id、nodes.title也会返回undefined - 文章标题存储在
frontmatter层级下,你没有取该层级直接读取title无法拿到正确值 pageContext是你传入的上下文对象,直接赋值给title会拿到对象而非标签名,需要读取pageContext.tags取值
修复方案(推荐,简化多余查询逻辑)
你已经按单个标签过滤了查询结果,完全不需要额外使用group聚合,直接获取文章列表即可,修改后的标签模板代码如下:
import { Link, graphql } from "gatsby" import * as React from "react" import Layout from "../components/layout/layout" const TagList = ({ pageContext, data }) => { const currentTag = pageContext.tags const posts = data.allMdx.nodes const postCount = posts.length return ( <Layout> <h3>标签:{currentTag}(共{postCount}篇文章)</h3> <ul> {posts.map(post => ( <li key={post.id}> <Link to={`/blog/${post.slug}`}>{post.frontmatter.title}</Link> </li> ))} </ul> <Link to="/blog">All tags</Link> </Layout> ); } export default TagList; export const query = graphql` query MyQuery($tags: String) { allMdx( filter: { frontmatter: { tags: { in: [$tags] } } } ) { nodes { id slug frontmatter { title } } } } `
修改完成后重启gatsby develop即可正常渲染对应标签的文章列表。
可选修复方案(保留原有group查询逻辑)
如果你不想修改现有GraphQL查询,只需要调整模板的数据读取逻辑即可:
import { Link, graphql } from "gatsby" import * as React from "react" import Layout from "../components/layout/layout" const TagList = ({ pageContext, data }) => { // 取分组的第一个(也是唯一一个)元素 const currentGroup = data.allMdx.group[0] const postCount = currentGroup.totalCount return ( <Layout> <h3>{currentGroup.fieldValue}(共{postCount}篇文章)</h3> <ul> {currentGroup.nodes.map(post => ( <li key={post.id}> <Link to={`/blog/${post.slug}`}>{post.frontmatter.title}</Link> </li> ))} </ul> <Link to="/blog">All tags</Link> </Layout> ); } // 原有查询保持不变即可 export const query = graphql` query MyQuery($tags: String) { allMdx( filter: { frontmatter: { tags: { in: [$tags] } } } ) { group(field: frontmatter___tags) { fieldValue totalCount nodes { id slug frontmatter { title } } } } } `
内容的提问来源于stack exchange,提问作者Judia
相关产品推荐
相关产品推荐

