【问题标题】:Apollo GraphQL failing connectionApollo GraphQL 连接失败
【发布时间】:2021-09-23 10:13:44
【问题描述】:

我的根组件已经用 ApolloProvider 标签包裹,但错误消息告诉我不是。

错误信息

Invariant Violation: Could not find "client" in the context or passed in as an option. Wrap the root component in an <ApolloProvider>, or pass an ApolloClient instance in via options.

This error is located at:
    in App (created by ExpoRoot)

问题是我的根组件已经被 ApolloProvider 标签包裹了

反应原生代码

IMPORT 语句

import {
  ApolloClient,
  InMemoryCache,
  useQuery,
  ApolloProvider,
  gql,
} from "@apollo/client";

与 GraphQL 的连接

const client = new ApolloClient({
  uri: "https://www.outvite.me/gql/gql",
  cache: new InMemoryCache(),
  defaultOptions: { watchQuery: { fetchPolicy: 'cache-and-network' } },
})

测试查询

const USER_QUERY = gql`
  query USER {
    users {
      nodes {
        edge {
          username
        }
      }
    }
  }
`

默认应用

这是抛出错误的地方

const { data, loading } = useQuery(USER_QUERY) 是 traceback 显示的那一行

export default function App() {
    const { data, loading } = useQuery(USER_QUERY)
    return (
        <ApolloProvider client={client}>
           <View>
             <Text style={styles.text}>Open</Text>
             <Text style={styles.text}>Another text</Text>
           </View>
           <Button title="Toggle Sidebar" onPress={() => toggleSidebarView()} />
           <Button title="Change theme" onPress={() => toggleColorTheme()} />
        </ApolloProvider>
    );
}

【问题讨论】:

  • 更严格地遵循 docs/tuts - 您正在尝试使用 hook 并稍后呈现 hook 提供程序所需的 - 您没有发现问题吗?

标签: graphql apollo apollo-client react-apollo react-apollo-hooks


【解决方案1】:

如果我没记错的话,useQuery 钩子仅在您位于已包含在 ApolloProvider 中的组件中时才有效,因此您可能想做这样的事情

export default function MainApp() {
    const { data, loading } = useQuery(USER_QUERY)
    return (
      <View>
        ... use 'data' in here somewhere...
      </View>
    );
}

然后顶级App 组件看起来像

export default function App() {
    return (
      <ApolloProvider client={client}>
        <MainApp />
      </ApolloProvider>
    );
}

【讨论】:

    猜你喜欢
    • 2022-10-13
    • 2020-09-19
    • 2020-10-18
    • 2019-04-25
    • 2019-12-10
    • 2018-06-03
    • 2022-07-07
    • 2021-07-22
    • 2023-01-30
    相关资源
    最近更新 更多