graphql - 在页面末尾使用命名导出时,Gatsby 页面查询无法工作。为什么?

标签 graphql gatsby es6-modules

我在 Gatsby 中有以下页面模板。

import React from 'react';
import { graphql } from 'gatsby';
import Layout from '../components/layout';

const PageTemplate = props => {
  const { wordpressPage: currentPage } = props.data;
  return (
    <Layout>
      <h1 dangerouslySetInnerHTML={{ __html: currentPage.title }} />
      <div dangerouslySetInnerHTML={{ __html: currentPage.content }} />
    </Layout>
  );
};

export const pageQuery = graphql`
  query($id: String!) {
    wordpressPage(id: { eq: $id }) {
      title
      content
      date(formatString: "MMMM DD, YYYY")
    }
    site {
      id
      siteMetadata {
        title
      }
    }
  }
`;

export default PageTemplate;

这按预期工作(取自教程),但是我倾向于在页面末尾进行所有导出,如下所示:

import React from 'react';
import { graphql } from 'gatsby';
import Layout from '../components/layout';

const PageTemplate = props => {
  const { wordpressPage: currentPage } = props.data;
  return (
    <Layout>
      <h1 dangerouslySetInnerHTML={{ __html: currentPage.title }} />
      <div dangerouslySetInnerHTML={{ __html: currentPage.content }} />
    </Layout>
  );
};

const pageQuery = graphql`
  query($id: String!) {
    wordpressPage(id: { eq: $id }) {
      title
      content
      date(formatString: "MMMM DD, YYYY")
    }
    site {
      id
      siteMetadata {
        title
      }
    }
  }
`;

export default PageTemplate;
export { pageQuery }

但是这不起作用 - props.data未定义。这是一个微妙的差异,但为什么这会导致 pageQuery 不执行?

最佳答案

我相信 pageQuery 必须在 PageTemplate 之前导出,因为它被它使用:这是它获取 props.data 的地方,这解释了为什么您在导出后会得到未定义

关于graphql - 在页面末尾使用命名导出时,Gatsby 页面查询无法工作。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58312296/

相关文章:

python - 在 Django 2.2 中为 GRAPHENE 设置 'SCHEMA' 导入模块时出现问题

node.js - Query.user 的类型必须是 Output Type 但得到 : undefined

javascript - 使用 GatsbyJS 的单页网站菜单中的事件类名

npm - VSCode 调试和 Jest : No breakpoints running with npm, 使用节点运行时出现 CWD 错误

reactjs - 构建失败 - 在 AWS Amplify 中 'npm build' 后检测到非零退出代码

javascript - 如何从 typescript 上的txt文件获取数据?

javascript - 如何知道 npm 包是否可以使用 ES6 导入语法导入?

spring-boot - 未创建 GraphQLSchema bean - Spring Boot

express - 将获取响应 header 转发到 Apollo graphql 响应

javascript - 如何在 IE 中避免模块导入