javascript - 如何使用 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;
解决方案
问题就在这里
render() {
return (
mainFunction()
);
}
mainFunction 的 return 语句不是反应组件,因此它始终是一个对象,因此您应该使用 JSON stringify 在 Text 中显示如下内容
render() {
return (
<View><Text>{JSON.stringify(mainFunction())}</Text></View>
);
}
一旦你得到响应,最好有一个状态并更新它,这是响应时的最佳实践
推荐阅读
- c++ - leetcode 问题 154 的运行时错误:重新排序列表
- ansible - Ansible yaml 制动长链接,如字符串,可变插值到多行
- javascript - Express JS 通过控制器函数传递中间件
- javascript - JS 正则表达式返回 -1 & 0
- javascript - 为什么小数字字符串大于大数字字符串
- python - python - 如何仅针对特定值在python中找到spearman的相关性?
- sql - 查询以将 DateTimestamp 列与另一个具有 StartDate 和 EndDate 的表连接起来
- html - 导航菜单在响应较小时无法显示列表
- css - 我是保留子主题还是仅移动/使用父主题?
- python - Dask 字典到延迟对象适配器