首页 > 解决方案 > ApolloConsumer VS 导入客户端

问题描述

为什么我应该使用 ApolloConsumer 而不是直接在我的模块中导入客户端?

从文档中我应该做类似的事情:

// Module A.js initiate client
const client = new ApolloClient({
  // init cache, links, typeDefs...
});
export default client;
// Module index.jsx
import client from 'A';

ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>, 
  document.getElementById('root'));
// Any other component not using Query or Mutation
const Other = () => (
  <ApolloConsumer>
  {
    client => {
      // use client
    }
  }
  </ApolloConsumer>);

但是为什么不直接导入没有 ApolloConsumer 的客户端呢?

// Module OtherBis
import client from 'A';

const AltOther () => {
  // do something with client
  return <div></div>;
};

标签: reactjsapollo-client

解决方案


在我看来,ApolloConsumer组件是为支持而创建的,JSX就像react-relayfor一样relay。没有必要。其实我从来没用过ApolloConsumer。此外,还有可以做任何事情的钩子(例如useQuery,、、useMutation) 。useSubscription他们只是做一个工具。是否使用它取决于您。


推荐阅读