【问题标题】:Zero results found: GraphQL query on live deploy with WordPress API and Gatsby on Netlify发现零个结果:在 Netlify 上使用 WordPress API 和 Gatsby 进行实时部署的 GraphQL 查询
【发布时间】:2020-11-06 15:45:53
【问题描述】:

我很困惑,为什么在 localhost:9000 上运行 gatsby build && gatsby serve 的本地开发中,我能够以编程方式创建类别页面,该页面根据类别 slug 变量查询和输出帖子列表,但是当我将网站部署到 Netlify,类别页面显示零结果,无论类别或有多少帖子与查询匹配。

// gatsby.node
exports.createPages = async ({ graphql, actions }) =>  {

    const { createPage } = actions
    const categoryTemplate = path.resolve('src/templates/categoryTemp.js')

    const result = await graphql(`
        query {
            allWordpressCategory {
                edges {
                    node {
                        id
                        path
                        slug
                        name
                        description
                    }
                }
            }
        }
    `)

    const { allWordpressCategory } = result.data

    allWordpressCategory.edges.forEach(({ node }) => {
        if (node.slug === 'portfolio') return
        createPage({
            path: node.path,
            component: categoryTemplate,
            context: {
                id: node.id,
                slug: node.slug,
                name: node.name,
                description: node.description,
                url: node.path
            }
        })
    })

createPage 操作中的 context 属性(包含类别的 slug)被传递给我设置的 categoryTemplate 页面/组件 (categoryTemp.js)。

slug 在 GraphQL 查询中用作过滤变量,应该返回与该类别匹配的所有帖子:

// src/templates/categoryTemp.js
import React from "react"
import { graphql, Link } from "gatsby"
import Layout from "../components/layout/layout"
import PageContent from "../components/layout/pageContent"

export default ({ data, pageContext }) => {

    const { allWordpressPost } = data 

    return (
        <Layout path={pageContext.url} layoutClass={"category"}>

            <PageContent>
                <h2>{allWordpressPost.totalCount} posts in category: {pageContext.name}</h2>
                <ul>
                    {allWordpressPost.edges.map(({ node }, idx ) => (
                        <li key={idx}><Link to={node.path} title={node.title}>{node.title}</Link></li>
                    ))} 
                </ul>
            </PageContent>
           
        </Layout>
    )

}

export const categoryQuery = graphql`
    query($slug: String!) {
        allWordpressPost(filter: {categories: {elemMatch: {slug: {eq: $slug}}}}) {
            edges {
                node {
                    id
                    title
                    path
                }
            }
            totalCount
          }
    }
`

正如我之前所说,这在本地开发中有效,当我运行gatsby build &amp;&amp; gatsby serve 时,这通常是一个很好的production test,以查看您的 gatsby 站点在服务器上的运行情况。但是,实时站点无法返回任何查询匹配项:

我想知道在以编程方式处理和创建这些类别模板时是否可能需要采取一些中间步骤,例如overriding the default context property,但恐怕我有点怀疑我能否弄清楚这一点立即或根本没有。

同样,我经常看到这种模式:Complex query variables in GraphQL (via Gatsby),但需要推动如何实现它。

有人有什么想法或建议吗?

// gatsby-config.js

module.exports = {
    siteMetadata: {
        ...
    },
    plugins: [
        `gatsby-plugin-react-helmet`,
        {
            resolve: `gatsby-source-filesystem`,
            options: {
                name: `images`,
                path: `${__dirname}/src/images`,
            },
        },
        `gatsby-transformer-sharp`,
        `gatsby-plugin-sharp`,
        {
            resolve: `gatsby-plugin-manifest`,
            options: {
                name: "Peak Websites",
                short_name: "Peak Websites",
                start_url: "/",
                background_color: "#27688E",
                theme_color: "#27688E",
                display: "minimal-ui",
                icon: "src/images/logo/Logo_squared.png",
            },
        },
        {
            resolve: `gatsby-source-wordpress`,
            options: {
                baseUrl: `pathtomysite.com`,
                protocol: `https`,
                useACF: false,
                verboseOutput: false,
                hostingWPCOM: false
            }
        },
        `gatsby-plugin-sass`,
        {
            resolve: `gatsby-plugin-prefetch-google-fonts`,
            options: {
                fonts: [{
                    family: `Montserrat`,
                    variants: [`300`,`300i`,`400`,`400i`,`700`]
                }],
            },
        }, {
            resolve: `gatsby-plugin-google-analytics`,
            options: {
                trackingId: process.env.GA_TRACKING_CODE,
                head: false,
            },
        },
        // `gatsby-plugin-sitemap`
        // this (optional) plugin enables Progressive Web App + Offline functionality
        // To learn more, visit: https://gatsby.dev/offline
        // `gatsby-plugin-offline`,
  ],
}

【问题讨论】:

    标签: reactjs graphql gatsby wordpress-rest-api netlify


    【解决方案1】:

    我为解决这个问题做了两个调整。

    首先,我将我的查询修改为gatsby-node.jsallWordpressPosts下的数据层查询categories &gt; slug,即:

    allWordpressPost {
        edges {
            node {
                id
                wordpress_id
                status
                path
                categories {
                    slug
                }
            }
        }
    }
    

    然后我在函数组件中写了一个过滤函数渲染匹配的帖子列表之前。

    const filteredPosts = allWordpressPost.edges.filter(({node}) => {
        return node.categories.some(({ slug }) => slug === pageContext.slug)
    })
    
    return (
            <Layout path={pageContext.url} layoutClass={"category"}>
    
                <PageContent>
                    <h2>{allWordpressPost.totalCount} posts in category: {pageContext.name}</h2>
                    <ul>
                        {filteredPosts.map(({ node }, idx ) => (
                            <li key={idx}><Link to={node.path} title={S(node.title).decodeHTMLEntities().s}>{S(node.title).decodeHTMLEntities().s}</Link></li>
                        ))}
                    </ul>
                </PageContent>
               
            </Layout>
        )
    

    pageContext 在构建时传递到每个类别页面并包含所有道具,包括我在createPages 操作中定义的slug

    createPage({
        path: node.path,
        component: categoryTemplate,
        context: {
            id: node.id,
            slug: node.slug,
            ...
        }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      • 2020-12-04
      • 2019-10-12
      • 2019-10-18
      • 2020-05-05
      • 1970-01-01
      • 2021-06-15
      相关资源
      最近更新 更多