求助:GraphQL中allMarkdownRemark无法使用field与order排序的解决办法
解决方案
1. 扩展GraphQL Schema添加排序字段
在项目根目录的gatsby-node.js中添加以下代码,自定义MarkdownRemarkSortInput类型,补上缺失的fields和order字段:
exports.createSchemaCustomization = ({ actions }) => { const { createTypes } = actions; const typeDefs = ` input MarkdownRemarkSortInput { fields: [String!] order: [SortOrder!] } enum SortOrder { ASC DESC } `; createTypes(typeDefs); };
重启Gatsby开发服务后,就能在GraphQL查询中使用类似这样的排序参数:
query MyQuery { allMarkdownRemark(sort: {fields: ["frontmatter.date"], order: ["DESC"]}) { nodes { frontmatter { date title } } } }
2. 前端手动排序数据
如果自定义Schema的方式不生效,可在获取数据后在组件内手动排序:
export const query = graphql` query { allMarkdownRemark { nodes { frontmatter { date title } id } } } `; const BlogPage = ({ data }) => { // 按日期降序排列 const sortedPosts = data.allMarkdownRemark.nodes.sort((postA, postB) => { return new Date(postB.frontmatter.date) - new Date(postA.frontmatter.date); }); return ( // 渲染排序后的内容 <div> {sortedPosts.map(post => ( <div key={post.id}> <h2>{post.frontmatter.title}</h2> <p>{post.frontmatter.date}</p> </div> ))} </div> ); }; export default BlogPage;
3. 检查依赖版本
确保gatsby-transformer-remark依赖为最新版本,旧版本可能未内置排序字段支持:
npm update gatsby-transformer-remark
同时确认你要排序的字段(比如frontmatter.date)在所有Markdown文件的frontmatter中都已定义,避免排序时出现空值错误。
内容的提问来源于stack exchange,提问作者Dariusz
相关产品推荐
相关产品推荐

