作者:A198806192616 | 来源:互联网 | 2022-12-02 13:56
1> coreyward..:
距离您不太远。GraphQL支持在同一查询中查询多个离散节点:
export const query = graphql`
{
products: allMarkdownRemark(
filter: { frontmatter: { type: { eq: "product" } } }
) {
edges {
# ...
}
}
pages: allMarkdownRemark(
filter: { frontmatter: { type: { eq: "pages" } } }
) {
edges {
# ...
}
}
}
`
请注意,我已经使用别名allMarkdownRemark
在同一GraphQL查询中使用单独的过滤器来获取同一初始节点()。这将导致data.products
并将data.pages
其传递到default
导出的React组件中。
要清理此问题,可以使用片段,使您可以products
在Carousel
文件中并置查询:
进入carousel.js
(或任何包含“轮播”组件的文件):
export const query = graphql`
fragment Products on Query {
products: allMarkdownRemark(
filter: { frontmatter: { type: { eq: "product" } } }
) {
edges {
# ...
}
}
}
`
然后在您的页面文件中:
export const query = graphql`
{
pages: allMarkdownRemark(
filter: { frontmatter: { type: { eq: "pages" } } }
) {
edges {
# ...
}
}
...Products
}
`
注意:如果您使用的是Gatsby 1.x,则需要on Query
将片段的部分更改为on RootQueryType
。
假设您使用的是Gatsby v2,则还可以使用StaticQuery而不是将查询合并为一个查询。如果您的页面与产品的轮播无关,则此功能特别有用。
import React from "react";
import { graphql, StaticQuery } from "gatsby";
class Carousel extends React.Component {
// ...
}
export default props => (
}
/>
);