ApolloProvider没有传递客户端实例-React Native

时间:2019-10-31 04:59:05

标签: react-native graphql apollo react-apollo apollo-client

我已经用GraphQL设置了我的React Native应用程序。一旦我开始新项目并按照带有响应本机的graphql设置,我就会收到此错误。

  

ApolloProvider没有传递客户端实例。确保您通过客户道具传递客户

我从上到下一直遵循这个documentation

apollo.js

import {HttpLink} from 'apollo-link-http';
import {ApolloClient} from 'apollo-client';
import {InMemoryCache} from 'apollo-cache-inmemory';

const makeApolloClient = token => {
  // create an apollo link instance, a network interface for apollo client
  const link = new HttpLink({
    uri: `https://learn.hasura.io/graphql`,
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });
  // create an inmemory cache instance for caching graphql data
  const cache = new InMemoryCache();
  // instantiate apollo client with apollo link instance and cache instance
  const client = new ApolloClient({
    link,
    cache,
  });
  return client;
};
export default makeApolloClient;

App.js

import React from 'react';
import AppContainer from '../routes/Routes';
import AsyncStorage from '@react-native-community/async-storage';
import {ApolloProvider} from 'react-apollo';
import makeApolloClient from '../apollo/apollo';

console.disableYellowBox = true;

class App extends React.Component {
  state = {
    client: null,
  };

  async componentDidMount() {
    // fetch session
    const session = await AsyncStorage.getItem('@todo-graphql:session');
    const sessionObj = JSON.parse(session);
    const {token, id} = sessionObj;
    // make apollo client with this session token
    const client = makeApolloClient(token);
    // start emitting events saying that the useri s online
    this.setState({client});
  }

  render() {
    return (
      <ApolloProvider client={this.state.client}>
        <AppContainer />
      </ApolloProvider>
    );
  }
}

export default App;

错误

enter image description here

"apollo-cache-inmemory": "^1.6.3",
"apollo-client": "^2.6.4",
"apollo-link-http": "^1.5.16",
"react": "16.9.0",
"react-apollo": "^3.1.3",
"react-native": "0.61.3",

1 个答案:

答案 0 :(得分:0)

渲染在componentDidMount之前被调用。因此,在第一个渲染期间,客户端实例将为null。这会导致错误。将渲染方法修改为

render() {
  if(!this.state.client) {
    return <Text>Loading</Text>
  }
  return (
      <ApolloProvider client={this.state.client}>
        <AppContainer />
      </ApolloProvider>
    );
}