怎么知道全局ApolloClient中所有query的networkStatus?

How can I know the networkStatus of all queries in ApolloClient globally?

我正在尝试在网络状态处于运行状态时显示预加载器。

我知道每个查询 returns 都有自己的网络状态,但在我的应用程序中有很多不同的查询。我想有一种方法可以在全球范围内处理所有查询的所有网络状态。

我想知道的是我的代码中的答案:"Is there any query pending on the network?"。

目前,没有办法做到这一点,至少 easily/built-in 没有。您可以在 https://github.com/apollographql/apollo-feature-requests.

上请求将其作为一项功能

根据您想要实现的目标,在 HttpLink 上使用 middleware/afterware 可能就足够了,例如:

import { ApolloLink } from 'apollo-link';

const middleware = new ApolloLink((operation, forward) => {
  console.log('Starting', operation);

  return forward(operation);
});

const afterware = new ApolloLink((operation, forward) => {
  return forward(operation).map(response => {
    console.log('Completed', operation);

    return response;
  });
});

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: ApolloLink.from([
    middleware,
    afterware,
    new HttpLink({ ... }),
  ]),
});

middleware 将在每个请求之前调用,afterware 将在之后调用。您可以在以下位置阅读有关链接的更多信息:https://www.apollographql.com/docs/link/.

或者,查看 Apollo 公开公开的一些 API,我能够以这种 "unofficial" 方式进行检查:

function queriesInFlight() {
  // client is your ApolloClient instance
  const { queryManager } = client;

  return Object.keys(queryManager.queryStore.getStore()).filter(queryId =>
    queryManager.checkInFlight(queryId),
  );
}

现在有一个图书馆可以做到这一点。 https://github.com/molindo/react-apollo-network-status