【发布时间】:2017-12-12 20:17:38
【问题描述】:
我最近刚开始研究 Relay Modern,并创建了一个带有 GraphQL 后端的简单应用程序(在使用 GraphIQL 进行测试时效果很好)。但是,我遇到了 Relay 不发送网络请求来检索 any 数据的问题。我对下面的代码不是 100% 有信心,但我肯定希望它至少向 http://localhost:3000/graphql 发送网络请求,但开发工具不会显示任何此类请求(或服务器日志)。
environment.js
import { Environment, Network, RecordSource, Store } from 'relay-runtime';
const store = new Store(new RecordSource());
const network = Network.create((operation, variables) =>
fetch('http://localhost:3000/graphql', {
method: 'POST',
headers: {
// Add authentication and other headers here
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: operation.text, // GraphQL text from input
variables,
}).then(res => res.json()),
})
);
const environment = new Environment({
network,
store,
});
export default environment;
App.jsx
import React, { Component } from 'react';
import { graphql, QueryRenderer } from 'react-relay';
import environment from '@utilities/environment';
class App extends Component {
render() {
console.log(this.props); // Empty object {} here
return (
<div>
Hello World!
</div>
);
}
}
const Query = graphql`
query AppQuery {
user(id: "u01") {
id
username
}
}
`;
const AppQuery = () =>
(<QueryRenderer
environment={environment}
graphql={Query}
variables={{}}
render={({ error, props }) => {
console.log(error, props); // Get (undefined, {}) here
if (error) {
return <div>{error.message}</div>;
} else if (props) {
return <App {...props} />;
}
return <div>Loading!</div>;
}}
/>);
export default AppQuery;
我是否遗漏了一些明显的东西?没有控制台/webpack 错误,并且应用程序可以正确呈现,但根本没有 GraphQL/Relay 数据。谢谢!
【问题讨论】:
标签: javascript reactjs graphql relay