我有一个使用graphql实现的动态导航条。通过使用distinct并将字段设置为frontmatter___category,然后使用.map(),我设法获得了这些类别。但是,graphql按字母顺序返回类别,但我想对它们的顺序进行排序。我正在考虑为每个类别创建一个index.md,可以用来对它们进行排序,但我不知道如何做到这一点。
使用不同的字段,下面是如何映射类别并创建导航条(我使用的是antd):
<Menu>
{data[section]['distinct'].map((category) =>(
<SubMenu
key={category}
title={category.replace('-', ' ')}
style={{
fontWeight: 700,
maxWidth: 250,
}}
>
{checkCategory(category)} //get the MD files that belongs to this category
</SubMenu>
))}
</Menu>以下是我的疑问:
categoryA: allMdx(
sort: {fields: frontmatter___order, order: ASC}
filter: {frontmatter: {section: {eq: "categoryA"}}}
) {
distinct(field: frontmatter___category)
edges {
node {
id
frontmatter {
category
path
title
}
}
}
}这是我的前端,顺序是排序导航栏中的md文件:
---
title: item 1
path: /section1/categoryA/item1
category: categoryA
section: section1
order: 1
---我的文件夹结构如下:
|---contents
| |---section1
| | |---categoryA
| | | |---item1.md
| | |---categoryB
| | | |---item2.md
| | |---categoryC
| | | |---item3.md
| | |---categoryD
| | | |---item4.md发布于 2022-02-22 06:02:38
默认情况下,sort GraphQL选项按字母顺序排序。在您的情况下,如果您想要默认顺序,只需删除以下行:
sort: {fields: frontmatter___order, order: ASC}将查询保留为:
categoryA: allMdx(
filter: {frontmatter: {section: {eq: "categoryA"}}}
) {
distinct(field: frontmatter___category)
edges {
node {
id
frontmatter {
category
path
title
}
}
}
}这将以获取的顺序返回类别。
另一个选项是在打印类别之前使用JavaScript sort()方法。类似于:
let sortedData = props.data.categoryA.edges.node.sort((a, b) => a.frontmatter.order - b.frontmatter.order);应用你的代码。这个想法依赖于不使用GraphQL排序,而是使用JavaScript的排序。
let sortedData= data[section]['distinct'].sort((a, b) => a.frontmatter.order - b.frontmatter.order));然后以同样的方式遍历sortedData。
{sortedData[section]['distinct'].map((category) =>(
<SubMenu
key={category}
title={category.replace('-', ' ')}
style={{
fontWeight: 700,
maxWidth: 250,
}}
>
{checkCategory(category)} //get the MD files that belongs to this category
</SubMenu>
))}https://stackoverflow.com/questions/71214798
复制相似问题