【问题标题】:Relay Modern isn't sending network request to GraphQL ServerRelay Modern 没有向 GraphQL Server 发送网络请求
【发布时间】: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


    【解决方案1】:

    我觉得你的环境还不错。

    可能有一些帮助:您可能想要创建一个 FragmentContainer 并设置/运行 Relay Compiler 以生成所需的 graphql 文件,以便 Relay 运行您的查询。

    您可能希望通过 FragmentContainer 与 App 声明和配置数据需求。您需要一个片段容器,因为您的数据在 App 中被屏蔽,因此无法通过 props 获得(see more 这里为什么它被屏蔽了)。

    您需要像这样使用createFragmentContainer():

    App = createFragmentContainer(
      App,
      graphql`
        fragment App_users on User { // The fragment name should follow the convention <FileName>_<propName>, so maybe you might the App component to an another file.
           user(id: "u01") {
            id
            username
          }
        }
      `,
    );
    

    将查询修改为:

    graphql`
      viewer {
        ...App_users_viewer
      }
    `
    

    完成后,您应该能够运行 Relay Compiler 并生成 graphql 生成的文件

    【讨论】:

      猜你喜欢
      • 2017-11-01
      • 2018-08-30
      • 2018-09-14
      • 2021-12-18
      • 2018-06-27
      • 2018-10-09
      • 2019-07-19
      • 1970-01-01
      • 2010-11-13
      相关资源
      最近更新 更多