在React应用程序中传递Apollo Client的推荐方法是什么?

时间:2017-03-12 21:46:07

标签: react-apollo

现在我正在使用HOC withApollo,如:

export default connect(mapStateToProps, mapDispatchToProps)(withApollo(withData(Browse)));

然后在那个组件中:

  render() {
    const { client } = this.props;
    <Button onPress={() => searchInterestsTab(client)} />

然后在该组件之外:

export const searchInterestsTab = (client) => {

^但是我发现这非常麻烦,必须将它传递给我的组件中的每个外部函数。

我不能只使用:

const apolloClient = new ApolloClient({...})
export default apolloClient;

然后:

import apolloClient from './apolloClient';

到处?

1 个答案:

答案 0 :(得分:1)

应该可以使用它:

import apolloClient from './apolloClient'

如果查看usage documantation,您会发现可以使用它。因此,index.js中您应该已经拥有的最可能的地方

const apolloClient = new ApolloClient({...})

我的apollo客户端实例化如下:

&#13;
&#13;
import ApolloClient, { addTypename } from 'apollo-client';

const createApolloClient = options => {
   return new ApolloClient(Object.assign({}, {
      queryTransformer: addTypename,
      dataIdFromObject: (result) => {
         if (result.id && result.__typename) {
            return result.__typename + result.id;
         }
         return null;
      },
   }, options))
};

export default createApolloClient;
&#13;
&#13;
&#13;

并在index.js中使用它:

&#13;
&#13;
...

const client = createApolloClient({
   networkInterface: networkInterface,
   initialState: window.__APOLLO_STATE__,
   ssrForceFetchDelay: 100,
});


....


export {
  client,
  ...
};
&#13;
&#13;
&#13;