在React中填充Github GraphQL (Gatsby)可以通过以下步骤完成:
gatsby new my-github-app
cd my-github-app
npm install @apollo/client graphql
GithubData.js
,并添加以下代码:import React from 'react';
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://api.github.com/graphql',
cache: new InMemoryCache(),
headers: {
Authorization: `Bearer YOUR_GITHUB_TOKEN`,
},
});
const GithubData = () => {
const [data, setData] = React.useState(null);
React.useEffect(() => {
client
.query({
query: gql`
query {
viewer {
login
repositories(first: 5) {
nodes {
name
description
}
}
}
}
`,
})
.then((result) => setData(result.data));
}, []);
if (!data) {
return <div>Loading...</div>;
}
return (
<div>
<h1>My Github Repositories</h1>
<ul>
{data.viewer.repositories.nodes.map((repo) => (
<li key={repo.name}>
<h3>{repo.name}</h3>
<p>{repo.description}</p>
</li>
))}
</ul>
</div>
);
};
export default GithubData;
GithubData
组件。在src目录下的pages
文件夹中创建一个新的文件,例如index.js
,并添加以下代码:import React from 'react';
import GithubData from '../components/GithubData';
const IndexPage = () => {
return (
<div>
<h1>Welcome to my Github App</h1>
<GithubData />
</div>
);
};
export default IndexPage;
gatsby develop
http://localhost:8000
,你将看到你的Github仓库数据被填充到页面中。这样,你就成功地在React中填充了Github GraphQL数据。这个例子使用了Apollo Client来发送GraphQL查询,并使用了Github的GraphQL API来获取用户的仓库数据。你可以根据自己的需求修改查询和展示的数据。
领取专属 10元无门槛券
手把手带您无忧上云