首页 > 解决方案 > GraphQL 查询以根据内容 Web 应用程序中的顺序对引用进行排序

问题描述

我正在尝试 Contentful 和 Gatsby。目标是创建一个网站,编辑可以在其中从各个部分构建登录页面。我有一个表示页面包装器的内容类型。此内容类型具有“Sections”字段,该字段类型为 References(many)。使用此字段,我可以链接多种内容类型。此链接的内容类型显示在另一个之下。编辑器可以通过拖放对它们重新排序。见截图:

在此处输入图像描述 但是,当我呈现这些内容类型时,此顺序不可见。默认情况下,顺序基于链接内容的创建日期。graphql 游乐场中有一些排序选项,但它们都没有反映我在页面包装器中的实际拖放顺序。这是我的 graphql 查询,以及映射和呈现这些部分的代码

import ...
const Sections = () => {
const data = useStaticQuery( 
    graphql`
        query Sections {
            allContentfulSection {
                edges {
                    node {
                        id
                        title
                        heroImage {
                            fluid(maxWidth: 750) {
                                ...GatsbyContentfulFluid
                            }
                        }
                    }
                }
            }
        }
    `
)

return (

    <div className="sections">
        {data.allContentfulSection.edges.map(edge => {
            return (
                <div className="section" key={edge.node.id}>
                    {edge.node.heroImage && (
                        <Img
                            className="featured"
                            fluid={edge.node.heroImage.fluid}
                            alt={edge.node.title}
                        />
                    )}
                    <h2>
                        {edge.node.title}
                    </h2>
                </div>
            )
        })}
    </div>

   )
 }

export default Sections

有人可以告诉我一个 graphql 查询,它对链接的引用进行排序,就像它们出现在父页面包装内容中一样?这应该是可能的吧?如果这对您呈现的网站上的任何内容都没有影响,为什么我们应该在内容丰富的 Web 应用程序中通过拖放重新排序引用?

标签: graphqlgatsbycontentful

解决方案


我的问题是,我没有查询页面包装,而是查询“部分”内容类型中的所有内容。

正确的代码是:

import...
const Sections = () => {
const data = useStaticQuery( 
    graphql`
        query MyQuery {
              contentfulPagesMedium(title: {eq: "Frontpage"}) {
                sectionss {
                  id
                  title
                        heroImage {
                            fluid(maxWidth: 750) {
                                ...GatsbyContentfulFluid
                            }   
                        }
                }
              }
            }
    `
    )

return (

    <div className="sections">
        {data.contentfulPagesMedium.sectionss.map(section => {
            return (
                <div className="section" key={section.id}>
                    {section.heroImage && (
                        <Img
                            className="featured"
                            fluid={section.heroImage.fluid}
                            alt={section.title}
                        />
                    )}
                    <h2>
                        {section.title}
                    </h2>
                </div>
            )
        })}
    </div>

   )
}

export default Sections

推荐阅读