0

我的根组件已经用 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 {
  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>
    );
}
4

1 回答 1

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>
    );
}
于 2021-07-19T00:35:54.693 回答