无法在Query的上下文中找到“client”或作为传递的props

时间:2018-04-15 21:50:07

标签: javascript reactjs react-native react-apollo

这就是我在我的本机应用程序中尝试实现apollo graphQL的方法。

但是我确实得到了错误

Could not find "client" in the context of Query or as passed props. Wrap the root component in an <ApolloProvider>

所以我认为我已经做到了这一点,但显然我很想念一些事情。

import React, { Component } from 'react'
import { ApolloProvider, graphql } from 'react-apollo'
import { ApolloClient } from 'apollo-client'
import { createHttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import gql from 'graphql-tag'

import Routes from './config/routes'

// Initialize the Apollo Client
const client = new ApolloClient({
  link: createHttpLink({ uri: 'http://localhost:3000' }),
  cache: new InMemoryCache()
})

// Define query types
const DATA_QUERY = gql`
  query {
    getVersion {
      version
    }
  }
`

export class App extends Component {
  render () {
    console.log(this.props)
    // ApolloProvider lets us use Apollo Client in descendant components
    return (
      <ApolloProvider client={client}>
        <Routes />
      </ApolloProvider>
    )
  }
}

// Inject query response as `this.props.data`
export default graphql(DATA_QUERY)(App)

2 个答案:

答案 0 :(得分:4)

在开始使用@apollo/react-hooks之后,我遇到了这个问题,试图为同一问题找到解决方案。由于错误的表述是相同的,因此我仍然会提供答案,以防它对某人有所帮助。

错误是内容周围缺少ApolloHooksProvider。我通过更改此方法进行了修复

<ApolloProvider client={client}>
    <Content />
</ApolloProvider>

对此

import { ApolloProvider as ApolloHooksProvider } from '@apollo/react-hooks'

<ApolloProvider client={client}>
    <ApolloHooksProvider client={client}>
        <Content />
    </ApolloHooksProvider>
</ApolloProvider>

答案 1 :(得分:2)

<ApolloProvider>不会将graphql(DATA_QUERY)应用程序包装在该组件内部。这样的事情应该有效:(尽管你可能想选择一个不同的名字)

const AppolloRoutes = graphql(DATA_QUERY)(Routes);

export default class App extends Component {
  render () {
    console.log(this.props)
    // ApolloProvider lets us use Apollo Client in descendant components
    return (
      <ApolloProvider client={client}>
        <AppoloRoutes />
      </ApolloProvider>
    )
  }
}