【问题标题】:Invariant Violation: Query(...): Nothing was returned from render. This usually means a return statement is missing不变违规:查询(...):渲染没有返回任何内容。这通常意味着缺少返回语句
【发布时间】:2019-08-18 20:34:57
【问题描述】:

我有一个组件名称是Graph.js 下面给出的代码:

import React, { Component } from "react";
import { View, Text } from "react-native";
import ApolloClient from "apollo-boost";
import { ApolloProvider } from "react-apollo";
import Launches from "./Launches.js";
const client = new ApolloClient({
  uri: "http://127.0.0.1:4000/graphql"
});

export default class Graph extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return (
      <ApolloProvider client={client}>
        <View>
          <Text>Hello Apillo</Text>
        </View>
        <Launches />
      </ApolloProvider>
    );
  }
}

另一个文件名是Launcher.js 代码如下:

import React, { Component } from "react";
import { View, Text } from "react-native";
import gql from "graphql-tag";
import { Query } from "react-apollo";

const LAUNCHES_QUERY = gql`
  query LaunchesQuery {
    launches {
      flight_number
      mission_name
    }
  }
`;
export default class Launches extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return (
      <View>
        <Query query={LAUNCHES_QUERY}>
          {({ loading, error, data }) => {
            if (loading) return <Text>Loading...</Text>;
            if (error) return console.log(error);
            let length = data.length;
            console.log(data);
            return <Text>Launches</Text>;
          }}
        </Query>
      </View>
    );
  }
}

我在本地主机中设置了graphql,它在http://localhost:4000/graphql 中运行良好。

当我从 react-native 应用调用 URI 时,它会生成错误。

Error1网络错误:网络请求失败

错误 2不变量违规:查询(...):渲染未返回任何内容。这通常意味着缺少 return 语句。或者,不渲染任何内容,返回 null。

我还尝试更改 URI http://localhost 并提供给 http://127.0.0.1

提前致谢

【问题讨论】:

  • 用机器ip试试
  • @GuruparanGiritharan 好的,我会检查的

标签: reactjs react-native graphql react-apollo apollo-client


【解决方案1】:

Query 组件必须在 之外,它是:

...
  render() {
    return (
      <Query query={LAUNCHES_QUERY}>
        {({ loading, error, data }) => {
          if (loading) return <Text>Loading...</Text>;
          if (error) return console.log(error);
          let length = data.length;
          console.log(data);
          return <Text>Launches</Text>;
        }}
      </Query>
    );
  }
  ...

【讨论】:

    【解决方案2】:

    Duverney 的回答可能对其他人有帮助,但我在 React Web 应用程序上也遇到了这个问题,如果没有数据,解决方法是专门返回 null。如果返回一个空字符串,它将失败。在 JSX 中包装返回值也解决了这个问题。希望这可以为其他人节省几分钟。

    【讨论】:

    • 嗨,Ben,您能举例说明一下吗?我会因为同样的错误而发疯,我的返回语法看起来是正确的......提前致谢!
    • 我想我必须查看您的代码才能显示任何有用的信息。你到底从渲染函数返回了什么?你不能什么都不返回(undefined),但你可以返回null
    • @joeCarpenter 查看此渲染函数以及处理数据的方式以及所有可能的返回场景正在编码:github.com/tehpsalmist/play-the-mind/blob/…
    • 谢谢 Ben,这是我发布的问题的链接:stackoverflow.com/questions/58785332/…
    猜你喜欢
    • 2021-06-24
    • 2019-07-04
    • 2018-08-11
    • 2021-09-10
    • 2020-07-11
    • 2020-08-02
    • 2021-07-25
    相关资源
    最近更新 更多