簡體   English   中英

WpGraphQL 查詢返回 null

[英]WpGraphQL query returns null

我通過 WpGraphQl 插件從 Nexjs 中的無頭 Wordpress 獲得了這個 GraphQL 查詢:

export const GET_POSTS_BY_CATEGORY_SLUG = gql`
 query GET_POSTS_BY_CATEGORY_SLUG( $slug: String, $uri: String, $perPage: Int, $offset: Int ) {
 ${HeaderFooter}
  page: pageBy(uri: $uri) {
    id
    title
    content
    slug
    uri
    seo {
      ...SeoFragment
    }
  }
  categories(where: {slug: $slug}) {
    edges {
      node {
        slug  
        posts: posts(where: { offsetPagination: { size: $perPage, offset: $offset }}) {
          edges {
            node {
              id
              title
              excerpt
              slug
              featuredImage {
                node {
                  ...ImageFragment
                }
              }
            }
          }
          pageInfo {
            offsetPagination {
              total
            }
          }
        }
      }
    }
  }
}
 ${MenuFragment}
 ${ImageFragment}
 ${SeoFragment}
 `;

這是我的getStaticProps function:

export async function getStaticProps(context) {
  

  const { data: category_IDD } = await client.query({
    query: GET_POSTS_BY_CATEGORY_SLUG,
  });
  

  const defaultProps = {
    props: {
      
      cat_test: JSON.parse(JSON.stringify([category_IDD])),
    },

    revalidate: 1,
  };

  return handleRedirectsAndReturnData(defaultProps, data, errors, "posts");
}

如果我在道具中這樣傳遞它:

const defaultProps = {
    props: {

      cat_test: category_IDD,
    },

我收到一條錯誤消息:

SerializableError: Error serializing `.cat_test` returned from `getStaticProps` in "/category/[slug]". Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.

但是當我JSON.parse作為上面的代碼時,我得到null

這個查詢有什么問題?

剛剛注意到$slug是一個字符串數組,所以這里應該是:

query GET_POSTS_BY_CATEGORY_SLUG( $slug: [String], $uri: String, $perPage: Int, $offset: Int )

而不是$slug: String

您實際上並沒有將$slug變量傳遞給查詢。 例如,如果你的頁面路由是/category/[slug].js你的getStaticProps應該是這樣的。

export async function getStaticProps(context) {
  const { slug } = context.params;

  const { data: category_IDD } = await client.query({
    query: GET_POSTS_BY_CATEGORY_SLUG,
    variables: { slug },
  });
  

  const defaultProps = {
    props: {
      
      cat_test: JSON.parse(JSON.stringify([category_IDD])),
    },

    revalidate: 1,
  };

  return handleRedirectsAndReturnData(defaultProps, data, errors, "posts");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM