使用 ApolloClient 从 useContext 挂钩导入一个简单变量

Importing a simple variable from the useContext hook using ApolloClient

我对反应还比较陌生,似乎无法从上下文中导入 client 变量。我有一个名为 federation.tsx 的文件,其中包含一些代码,我认为这应该是相关部分:

const link = createHttpLink({
  uri: process.env.URL,
});

const useApolloClient = (user: User | null) => {
  const authLink = setContext((_, { headers }) => {
    return {
      headers: {
        ...headers,
        Authorization: user?.idToken || "",
      },
    };
  });
  return new ApolloClient({
    link: authLink.concat(link as any),
    cache: cache,
    name: "Test",
    version: process.env.ANOTHER_URL,
  });
};

export const FederationProvider: React.FC = ({children}) => {
  const [acc] = useContext(UserContext);
  const client = useApolloClient(acc);
  return <ApolloProvider client={client}>{children}</ApolloProvider>;
};

还有我的主应用程序文件,上下文提供程序包装了所有相关内容:

function App() {
  return (
    <div className="App">
            <FederationProvider>
                  <Router>
                    <Routes/>
                  </Router>
            </FederationProvider>
    </div>
  );
}

以及我尝试使用它的文件:

import React, {useContext, useEffect} from "react";
import {FederationProvider} from "..src";

export const someComponent(() => {
    const [client] = useContext(FederationProvider); // not working

    return (<>...</>)
})

任何人都可以发现我可能做错的明显事情吗?我不确定如何简单地导入客户端变量。

在文档中,它说要使用通过 ApolloProvider 配置的客户端,方法是使用 useApolloClient 挂钩,如下所示:-

const client = useApolloClient();

文档 - https://www.apollographql.com/docs/react/api/react/hooks/#useapolloclient