【问题标题】:What is the recommended way to pass Apollo Client around in a React app?在 React 应用程序中传递 Apollo Client 的推荐方法是什么?
【发布时间】:2017-03-13 15:36:38
【问题描述】:

现在我正在使用 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';

无处不在?

【问题讨论】:

    标签: react-apollo


    【解决方案1】:

    应该可以将它与以下类型一起使用:

    import apolloClient from './apolloClient'

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

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

    我的 apollo 客户端是这样实例化的:

    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;

    index.js 中是这样使用的:

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

    【讨论】:

    • 是的,这对我来说更有意义。那么 HOC 包装器“withApollo”的意义何在? >.
    • 如果您将 apollo 客户端与 favorite framework 一起使用,您通常不会使用 HOC。仅在某些特殊情况下,例如,如果您的组件具有突变作为道具。比你可以通过 HOC 调用突变
    猜你喜欢
    • 2013-04-04
    • 1970-01-01
    • 2012-08-26
    • 2023-03-06
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多