gpt4 book ai didi

react-native - ApolloProvider 未通过客户端实例 - React Native

转载 作者:行者123 更新时间:2023-12-02 04:22:27 24 4
gpt4 key购买 nike

我已经使用 GraphQL 设置了我的 React Native 应用程序。一旦我开始新的项目并使用 react native 遵循 graphql 的设置,我就会收到此错误。

ApolloProvider was not passed a client instance. Make sure you pass in your client via the client prop



我已关注此 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",

最佳答案

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

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

关于react-native - ApolloProvider 未通过客户端实例 - React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58637132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com