我一直在遵循这个Gatsby教程来根据我的CMS创建的标记文件动态创建页面:https://www.gatsbyjs.org/docs/adding-markdown-pages/
我不明白blogTemplate.js文件中的GraphQL查询是如何接收$path变量的。我可以看到,gatsby-node.js中的createPages函数根据自己的GraphQL查询结果创建页面,并使用“path”前沿元素为创建的页面选择URL。
但是,创建的页面如何知道自己的路径?本教程中名为pageQuery的查询使用$path变量来获取自己的数据,但我看不出它是如何接收该变量的。谢谢您的任何解释。
发布于 2020-05-08 17:59:22
在创建页面时,我们可以传递上下文,All context values are made available to a template’s GraphQL queries as arguments prefaced with $
exports.createPages = async function ({ actions, graphql }) {
const { data } = await graphql(`
query {
allMarkdownRemark {
edges {
node {
fields {
slug
}
}
}
}
}
`)
data.allMarkdownRemark.edges.forEach(edge => {
const slug = edge.node.fields.slug
actions.createPage({
path: slug,
component: require.resolve(`./src/templates/blog-post.js`),
context: { path: slug }, //here you can pass path through context parameter, the slug can be then accesed under $path variable in the template
})
})
}
`使用$符号,我们可以访问模板端的路径值。
export const query = graphql`
query($path: String!) {
...
}
`发布于 2020-05-08 18:05:23
Graphql使用redux internall,所有有关页面创建和路径的信息都被更新到gatsby的redux存储区,并从其上对每个页面执行graphql查询。
根据gatsby createPage github code comment的说法
在运行页面查询时,“上下文”中的
数据作为潜在的参数传递给GraphQL。
当构造GraphQL的参数时,context对象与页面对象组合在一起,因此页面对象和上下文数据都可用作为参数。因此,您不需要将页面"path“添加到上下文中,因为它已经在GraphQL中可用。如果上下文字段与页对象已经使用的字段重复,这可能会破坏盖茨比的功能,因此必须避免.
https://stackoverflow.com/questions/61684538
复制相似问题