[英]Display user's GitHub repositories in React App
我對React還是很陌生,我構建了一個GitHub搜索應用程序,您可以在搜索框中輸入用戶名,它顯示了他們的頭像,生物,用戶名等,但不知道如何獲取他們的GitHub存儲庫並顯示它們。
我在我的無狀態功能組件之一中獲取數據,以獲取回購數據,我什至可以做一個console.log,它將顯示數據,但實際上映射和呈現它似乎不起作用。
這是我一直在嘗試獲取數據的RepoList組件中嘗試的代碼:
import React, { Component } from 'react';
import RepoListItem from './RepoListItem';
const RepoList = (props) => {
const repoUserName = props.username;
const repoURL = props.reposURL;
fetch(`https://api.github.com/users/${repoUserName}/repos`)
.then(response => response.json())
.then(data => {
//const id = dateData.photos.map(roverdata => roverdata.id);
console.log("getting mappedrepo array IDs", data.map((mappedData) => mappedData.id ));
const mappedIDs = data.map((mappedData) => mappedData.id );
const mappedRepoNames = data.map((mappedData) => mappedData.full_name );
console.log("getting mappedrepo array names", mappedRepoNames);
const arrayItems = data.map((arraySingleItem) => {
return (
<RepoListItem
arrayID={arraySingleItem.id}
key={arraySingleItem.id}
fullName={arraySingleItem.full_name}
/>
);
});
console.log("repo data map function", repoData);
});
return (
<ul>
<h4>Repos</h4>
<a href={repoURL} className="embed-responsive-item">{repoURL}</a>
<br />
<br />
<h3>List of repositories</h3>
{arrayItems}
</ul>
);
};
export default RepoList;
我在以下網址上部署到Heroku的應用程序的工作版本略有不同: https : //githubsearchv1.herokuapp.com/ ,實際代碼在https://github.com/aalfr494/githubsearchv1
知道嘗試什么嗎? 在return函數中執行{arrayItems}似乎會給出一個錯誤,指出它未定義...是因為我在fetch塊中做了所有這些事情嗎? 任何想法都會幫助很多。
你可以用react-hooks
您可以像這樣使用useEffect()
進行api調用,
import React, { useState, useEffect } from 'react';
const RepoList = () => {
const [arrayItems, setArrayItems] = useState([]);
useEffect( async()=>{
await fetch(`https://api.github.com/users/${repoUserName}/repos`)
.then(response => response.json())
.then(data => {
const items= data.map((arraySingleItem) => {
return (
<RepoListItem
arrayID={arraySingleItem.id}
key={arraySingleItem.id}
fullName={arraySingleItem.full_name}
/>
);
});
setArrayItems(items);
})
}
}
return (
<ul>
<h4>Repos</h4>
<a href={repoURL} className="embed-responsive-item">{repoURL}</a>
<br />
<br />
<h3>List of repositories</h3>
{arrayItems}
</ul>
);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.