首页 > 解决方案 > 如何使用 GraphQL 和 React Native 从 GitHub 获取你的名字?

问题描述

我正在尝试使用 GraphQL 和 React Native 获取我的 GitHub 用户名。我不断收到错误消息“对象作为 React 子项无效。” 我曾尝试声明一个数组并将结果附加到该数组,但我只得到一个空数组。因此,我不能 100% 确定我是否正确获取数据。我还尝试在 mainFunction() 以及我可以在互联网上找到的每个建议的解决方案周围加上花括号,但似乎没有任何效果。我怎样才能让它工作?

import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { Navigation } from 'react-native-navigation';
import { ApolloClient } from 'apollo-boost';

var asynchronousFunction = async () => {
  var response = await fetch('https://api.github.com/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'bearer ' + {TOKEN},
    },
    body: '{ "query": "{ viewer { name } } "}',
  });
  return response;
};

var mainFunction = async () => {
  var result = await asynchronousFunction();
  return result;
};

(async () => {
  console.log(await mainFunction());
})();

class Example extends Component {
  render() {
    return (
      <View>
        <Text>{JSON.stringify(mainFunction())}</Text>
      </View>
    );
  }
}

export default Example;

标签: javascriptfunctionreact-nativerendering

解决方案


问题就在这里

 render() {
    return (
      mainFunction()
    );
  }

mainFunction 的 return 语句不是反应组件,因此它始终是一个对象,因此您应该使用 JSON stringify 在 Text 中显示如下内容

 render() {
    return (
      <View><Text>{JSON.stringify(mainFunction())}</Text></View>
    );
  }

一旦你得到响应,最好有一个状态并更新它,这是响应时的最佳实践


推荐阅读