使用 apollo 客户端创建 React 应用程序没有得到任何响应

create react app with apollo client doesn't get any response

我正在使用 create-react-app with apollo client and I followed the coding which is on apollo docs。 我的服务器配置 apollo server with express and I tested it followed the GraphQL Clients way. It works but when I tried to use apollo client way 它不起作用。这是我的代码。

在index.js文件中

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import ApolloClient from 'apollo-boost';
import {ApolloProvider} from 'react-apollo';

const client = new ApolloClient({
    uri: `/graphql`
});

ReactDOM.render(<ApolloProvider client={client}><App /></ApolloProvider>, document.getElementById('root'));

在 App.js 文件中

import gql from 'graphql-tag';
import {Query} from 'react-apollo';

const callQuery = gql`
{ 
  hello 
}
`;

class App extends Component {
  constructor(props) {
    super(props)
  }
  componentDidMount() {
    const test = this.HelloApi();
    console.log(test);
  }

  HelloApi() {
    <Query query={callQuery}>
      {({loading, error, data}) => {
        if(error) return `Error!: ${error}`;

        return data;
      }}
    </Query>
  }

render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;

我无法通过控制台和网络获得任何响应。请让我知道我错过了什么。谢谢。

如果您想在生命周期方法中测试查询,我会使用高阶组件"withApollo"

#withApollo

import gql from 'graphql-tag';
import {Query, withApollo} from 'react-apollo';

const callQuery = gql`
{ 
  hello 
}
`;

class App extends Component {
  constructor(props) {
    super(props)
}
  componentDidMount() {
    const test = this.props.client.query({ query: callQuery })
    console.log(test);
}

render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default withApollo(App);

通过这样做,您将可以在生命周期方法中访问客户端 "componentDidMount()"

你可以做到:

componentDidMount() {
    const test = this.props.client.query({ query: callQuery })
    console.log(test);
}