我将create-react-app与apollo 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'));
http://localhost:4000/graphql
或http://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;
我无法通过控制台和网络得到任何答复。请让我知道我想念的东西。谢谢。
答案 0 :(得分:0)
如果要在生命周期方法中测试查询,我将使用高阶组件“ 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);
}