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

问题描述 投票:0回答:1

我正在使用create-react-appapollo client,我遵循apollo docs上的编码。我的服务器配置为apollo server with express,我按照GraphQL Clients的方式测试了它。它工作,但当我尝试使用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'));
  • 我已经尝试改变uri,如http://localhost:4000/graphqlhttp://localhost:4000

在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;

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

reactjs graphql react-apollo apollo-client
1个回答
0
投票

如果你想在生命周期方法中测试一个查询,我会使用更高阶的组件“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);
}
© www.soinside.com 2019 - 2024. All rights reserved.