【问题标题】:Where does the variable slug comes from in gatsby graphql query?gatsby graphql 查询中的变量 slug 来自哪里?
【发布时间】:2019-10-25 07:41:32
【问题描述】:

我们在gatsby-node.js 中创建slug 节点。然后我们创建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",
      },
    })
  })

在模板中我们运行这样的东西。

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

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

graphql 怎么知道有蛞蝓?如果它做了类似this.props.pageContext.slug 之类的事情,那很好,但是在后台发生了什么?

变量$slug 是如何填充的?

【问题讨论】:

    标签: reactjs graphql gatsby


    【解决方案1】:

    要向页面组件查询添加变量,请在创建页面时将这些变量传递到上下文对象中。

    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",
        },
      })
    })
    

    【讨论】:

    • 谢谢。我得到了那部分,我想知道query($slug: String!) ... 是如何理解它应该在没有类似this.context.slug 的情况下查看上下文的
    猜你喜欢
    • 2021-07-03
    • 2021-01-15
    • 2019-10-13
    • 2020-11-30
    • 2021-11-24
    • 2020-03-23
    • 2019-02-14
    • 1970-01-01
    • 2019-11-22
    相关资源
    最近更新 更多