簡體   English   中英

如何使用 GraphQL 和 React Native 從 GitHub 獲取你的名字?

[英]How to get your name from GitHub using GraphQL and React Native?

我正在嘗試使用 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 在文本中顯示如下內容

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

最好有一個狀態並在收到響應后更新它,這是響應時的最佳實踐

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM