Apollo GraphQL 连接失败

问题描述

我的根组件已经用 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) 是回溯显示的行

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>
    );
}

解决方法

如果我没记错的话,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>
    );
}