javascript - graphql 标签中不允许字符串插值。 ( Gatsby )

标签 javascript reactjs graphql interpolation gatsby

尝试在我的 graphql 查询中为长而复杂的 Id 使用别名:
编译失败:graphql 标签中不允许字符串插值:

const query = graphql`
  query MyQuery {
    wordpress {
      menu(id: "${wordpress("mainMenu")}") {
        ...rest of query
      }
    }
  }
`

最佳答案

您应该改用查询变量。

Variables can be added to page queries (but not static queries) through the context object that is an argument of the createPage API. docs

// inside template file
export const query = graphql`
  query MyQuery($id: String!) {
    menu(id: { eq: $id }) {
        ...rest of query
    }
  }
`
然后你可以在 gatsby-node.js 中提供这样的变量作为页面上下文的一部分.例如:
// gatsby-node.js
const postTemplate = path.resolve(`./src/templates/post.js`)
allWordpressPost.edges.forEach(edge => {
  createPage({
    path: `/${edge.node.slug}/`,
    component: slash(postTemplate),
    context: {
      id: edge.node.id, // 👈
    },
  })
})
看看这个 using-wordpress example来自 Gatsby 。

关于javascript - graphql 标签中不允许字符串插值。 ( Gatsby ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62629823/

相关文章:

javascript - 如何在 React 组件中的多个按钮上使用 MDCRipple.attachTo

java - 生成的 GraphQL 类实现查询接口(interface)而不是订阅接口(interface)

javascript - 如何让 HTML 按钮依次运行三个功能

javascript - 无论我选择什么,复选框总是被选中

reactjs - 自定义箭头 Swiper Slider + Next.js + Sass

javascript - 当组件在 View 中时在 react-spring 中启动动画

graphql - buildSchema 和 makeExecutableSchema 有什么区别

json - 我应该在 GraphQL 中使用 Ints 来表示货币值吗?

javascript - 滚动上的动画 SVG

javascript - 检索 Bootstrap 轮播中的隐藏值