简体   繁体   English

gatsby graphql查询中变量slug来自哪里?

[英]Where does the variable slug comes from in gatsby graphql query?

We create the slug node in gatsby-node.js . 我们在gatsby-node.js创建gatsby-node.js节点。 Then we create the createPage 然后我们创建createPage

  const posts = result.data.allMarkdownRemark.edges
  posts.forEach(({ node: post }) => {
    createPage({
      path: `posts${post.fields.slug}`,
      component: PostTemplate,
      context: {
        slug: post.fields.slug,
        testingSomething: "this is a test",
      },
    })
  })

In the template we run something like this. 在模板中,我们运行类似的内容。

const PostTemplate = ({ data: post }) => {
  return ( ...)  }

export const query = graphql`
  query($slug: String!) {
    markdownRemark(fields: { slug: { eq: $slug } }) {
      ...
  }
`
export default PostTemplate

How does graphql know that there's a slug? graphql如何知道有一个? If it did something like this.props.pageContext.slug fine, but what's going on under the hud? 如果它执行类似this.props.pageContext.slug ,但是在平视this.props.pageContext.slug下发生了什么呢?

How does the variable $slug get populated? 变量$slug如何填充?

To add variables to page component queries, pass these in the context object when creating pages. 要将变量添加到页面组件查询中,请在创建页面时在上下文对象中传递这些变量。

Query variables 查询变量

const posts = result.data.allMarkdownRemark.edges
posts.forEach(({ node: post }) => {
  createPage({
    path: `posts${post.fields.slug}`,
    component: PostTemplate,
    context: {
      slug: post.fields.slug,
      testingSomething: "this is a test",
    },
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM