4

我正在尝试使用 Gatsby 从 GraphQL 查询数据。我按照Gatsby 的说明使用 GraphQL 查询页面中的数据,但是我不断收到错误消息。

错误(这是我需要解决的问题,而不是下面的示例):

错误:无法使用来自另一个模块或领域的 GraphQLObjectType“__Directive”。确保 node_modules 目录中只有一个“graphql”实例。如果不同版本的“graphql”是其他依赖模块的依赖,使用“resolutions”确保只安装一个版本。
https://yarnpkg.com/en/docs/selective-version-resolutions 不能同时使用重复的“graphql”模块,因为不同的
版本可能具有不同的功能和行为。来自另一个版本的函数中使用的数据可能会产生令人困惑和虚假的结果。

知道为什么会这样吗?我的 node_modules 文件夹中只有一个 graphql 实例

我正在使用的示例:

我将从 GraphQL 导入我自己的数据,但现在作为概念证明,我正在研究这个 Gatsby Rick and Morty 示例(上面的链接 - 我还没有打扰 axios 演示)。

index.js 代码:

import React, { Component } from 'react'
import { graphql } from 'gatsby'

// This query is executed at build time by Gatsby.
export const GatsbyQuery = graphql`
  {
    rickAndMorty {
      character(id: 1) {
        name
        image
      }
    }
  }
`

class ClientFetchingExample extends Component {
  render() {
    const {
      rickAndMorty: { character },
    } = this.props.data

    return (
      <div style={{ textAlign: "center", width: "600px", margin: "50px auto" }}>
        <h1>{character.name} With His Pupper</h1>
        <p>Rick & Morty API data loads at build time.</p>
        <div>
          <img
            src={character.image}
            alt={character.name}
            style={{ width: 300 }}
          />
        </div>
        <h2>Image of Rick's pupper</h2>
        <p>This will come from a request on the client</p>
      </div>
    )
  }
}

export default ClientFetchingExample

盖茨比-config.js:

plugins: [
  {
    resolve: "gatsby-source-graphql",
    options: {
      typeName: "RMAPI",
      fieldName: "rickAndMorty",
      url: "https://rickandmortyapi-gql.now.sh/",
    },
  },
...
4

2 回答 2

11

我的问题是关于错误而不是代码(我根据上下文请求添加了代码)。错误已解决,说明如下。

我首先检查我yarn.lockgraphql实例。(我有两个版本graphql)。错误说应该只有一个。

要解决这个问题:

1)我将以下内容添加到我的 package.json 中:

"resolutions": {
  "graphql": "^14.1.0"
}

2)我跑了npm install

这为我解决了错误,并希望对其他人有所帮助。


旁注:另一种方法来查找您的 node_modules 中可能拥有的版本find node_modules -name graphql在终端中运行。

对我来说,它返回了两个实例(不确定 gatsby 来自哪里):

node_modules/graphql
node_modules/gatsby/node_modules/graphql

要查找版本,请使用grep version node_modules/graphql/package.json

这就是我发现我正在运行 GraphQL 14.1.0

于 2019-03-06T15:38:52.790 回答
3

我检查了https://rickandmortyapi-gql.now.sh/并发现您的查询有错误。它应该是这样的:

export const GatsbyQuery = graphql`
  query rickAndMorty {
    character(id: 1) {
      name
      image
    }
  }
`

我猜你试图进行命名查询,但创建了错误。

plugins: [
  {
    resolve: "gatsby-source-graphql",
    options: {
      typeName: "RMAPI",
      fieldName: "character",
      url: "https://rickandmortyapi-gql.now.sh/",
    },
  },

...

于 2019-03-05T21:02:04.810 回答