这是我从无头 wordpress 获取帖子的 Graphql 查询:
export const GET_POSTS = gql`
query GET_POSTS( $uri: String, $perPage: Int, $offset: Int, $categoryId: Int ) {
posts: posts(where: { categoryId: $categoryId, offsetPagination: { size: $perPage, offset: $offset }}) {
edges {
node {
id
title
excerpt
slug
featuredImage {
node {
...ImageFragment
}
}
categories {
edges {
node {
categoryId
name
}
}
}
}
}
pageInfo {
offsetPagination {
total
}
}
}
}
${ImageFragment}
`;
当我这样做时:console.log("DATAAAA", data.posts.edges);
我得到:
DATAAAA [
{
node: {
id: 'cG9zdDo0MA==',
title: 'postttt',
excerpt: '<p>dlkfjdsflkdslkdjfkldsf</p>\n',
slug: 'postttt',
featuredImage: null,
categories: [Object],
__typename: 'Post'
},
__typename: 'RootQueryToPostConnectionEdge'
},
{
node: {
id: 'cG9zdDox',
title: 'Hello world!',
excerpt: '<p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p>\n',
slug: 'hello-world',
featuredImage: null,
categories: [Object],
__typename: 'Post'
},
__typename: 'RootQueryToPostConnectionEdge'
}
]
但是当尝试更进一步,里面node
,像这样:console.log("DATAAAA", data.posts.edges.node);
为了得到categoryId
里面的内容categories: [Object]
,我得到了未定义。
如何获得categoryId
基于此查询?
我想要做的是只获取给定类别的帖子getStaticProps
,但我不知道如何categoryId
动态获取。这就是我的getStaticProps
函数的样子:
export async function getStaticProps(context) {
console.log("THE CONTEXT", context);
const { data, errors } = await client.query({
query: GET_POSTS,
variables: {
uri: context.params?.slug ?? "/",
perPage: PER_PAGE_FIRST,
offset: null,
categoryId: <===== How to get this dynamically?
},
});
const defaultProps = {
props: {
data: data || {},
},
revalidate: 1,
};
return handleRedirectsAndReturnData(defaultProps, data, errors, "posts");
}
这是我的getStaticPaths
功能:
export async function getStaticPaths() {
const { data } = await client.query({
query: GET_CATEGORY_SLUGS_ID,
});
const pathsData = [];
data?.categories?.edges.node &&
data?.categories?.edges.node.map((category) => {
if (!isEmpty(category?.slug)) {
pathsData.push({ params: { slug: category?.slug } });
}
});
return {
paths: pathsData,
fallback: FALLBACK,
};
}
这就是我从上下文中得到的console.log("THE CONTEXT", context);
:
THE CONTEXT {
params: { slug: 'uncategorized' },
locales: undefined,
locale: undefined,
defaultLocale: undefined
}
任何帮助,将不胜感激。