如何使用 Apollo Client 访问应用程序中任何位置的“client”对象?

Noo*_*oob 6 apollo reactjs react-apollo apollo-client

我有一个使用 Apollo Client v1 的基本应用程序:

const client = new ApolloClient({...

...

<ApolloProvider client={client}>
   <App />
</ApolloProvider>,
Run Code Online (Sandbox Code Playgroud)

我想知道如何让我的应用程序的其余部分访问该client对象,以便他们可以使用client.query?

导出客户端然后将其导入另一个文件中的唯一方法吗?

由于我的应用程序包装在 a 中ApolloProvider,我想可能有一种client使用 Apollo 特定导入进行导入的方法?

小智 15

import { useApolloClient } from '@apollo/client';

function SomeComponent() {
  const client = useApolloClient();
  // `client` is now set to the `ApolloClient` instance being used by the
  // application (that was configured using something like `ApolloProvider`)
}
Run Code Online (Sandbox Code Playgroud)