📜  如何使用 react 制作 github api - Javascript (1)

📅  最后修改于: 2023-12-03 15:23:57.458000             🧑  作者: Mango

如何使用 React 制作 Github API

React 是一个非常流行的前端框架,它可以用来快速构建复杂的 UI。Github API 是一个非常有用的工具,它可以让我们在项目中获取 Github 上的数据。

在本教程中,我们将使用 React 和 Github API 来构建一个简单的应用程序。

设置 Github API

首先,我们需要从 Github 中生成一个 Access Token。这个 Token 将用于访问 Github API。

  1. 登录你的 Github 帐号。
  2. 点击右上角的帐号设置,选择 Settings。
  3. 在左侧菜单中选择 Developer settings。
  4. 在左侧菜单中选择 Personal access tokens。
  5. 点击 Generate new token 按钮。
  6. 在 Token description 输入框中输入描述信息。
  7. 在选择 scopes 中,选择需要访问的权限。
  8. 单击 Generate token 按钮。现在,你有了一个新的访问令牌。请不要泄露该令牌。
创建 React 应用程序

现在,我们将使用 Create React App 来创建一个新的 React 应用程序。运行以下命令:

npx create-react-app my-app
cd my-app
npm start

这将创建一个名为 my-app 的新应用程序,并启动一个开发服务器。

获取 Github 用户数据

我们需要获取某个 Github 用户的数据。我们将在 App 组件的 constructor 中初始化该用户数据。

constructor(props) {
  super(props);
  this.state = {
    user: null,
    loading: true,
    error: null
  };
  this.fetchUser = this.fetchUser.bind(this);
}

上面的代码中,我们初始化了三个状态:user、loading 和 error。fetchUser 是一个函数,它将从 Github API 请求用户数据。

fetchUser() {
  const { REACT_APP_GITHUB_ACCESS_TOKEN: accessToken } = process.env;
  const userLogin = 'torvalds';
  const apiUrl = `https://api.github.com/users/${userLogin}?access_token=${accessToken}`;

  fetch(apiUrl)
    .then(response => response.json())
    .then(user => this.setState({ user, loading: false }))
    .catch(error => this.setState({ error, loading: false }));
}

我们使用 fetch 函数来获取用户数据,并在返回用户数据时通过 setState 将其设置到组件的状态中。如果出现错误,则将错误信息设置到状态中。

最后,我们在 componentDidMount 生命周期方法中调用 fetchUser:

componentDidMount() {
  this.fetchUser();
}
显示 Github 用户数据

现在我们已经成功地获取 Github 用户数据,并将其保存在我们的组件状态中,我们可以在 render 函数中使用它。

首先,我们添加一些样式,用于展示用户数据。

.user-card {
  display: flex;
  padding: 16px;
  border: 1px solid #eaeaea;
  border-radius: 4px;
}

.user-avatar {
  width: 72px;
  height: 72px;
  margin-right: 16px;
  border-radius: 36px;
}

.user-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

然后,我们根据用户状态来显示用户数据:

render() {
  const { user, loading, error } = this.state;

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div className="user-card">
      <img className="user-avatar" src={user.avatar_url} alt={user.login} />
      <div className="user-info">
        <div>{user.name}</div>
        <div>{user.login}</div>
        <div>{user.bio}</div>
      </div>
    </div>
  );
}

上面的代码中,我们根据用户的状态来显示一个加载中的消息、错误信息或用户数据。

完整代码

完整的代码如下:

import React from 'react';

import './App.css';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: null,
      loading: true,
      error: null
    };
    this.fetchUser = this.fetchUser.bind(this);
  }

  componentDidMount() {
    this.fetchUser();
  }

  fetchUser() {
    const { REACT_APP_GITHUB_ACCESS_TOKEN: accessToken } = process.env;
    const userLogin = 'torvalds';
    const apiUrl = `https://api.github.com/users/${userLogin}?access_token=${accessToken}`;

    fetch(apiUrl)
      .then(response => response.json())
      .then(user => this.setState({ user, loading: false }))
      .catch(error => this.setState({ error, loading: false }));
  }

  render() {
    const { user, loading, error } = this.state;

    if (loading) {
      return <div>Loading...</div>;
    }

    if (error) {
      return <div>Error: {error.message}</div>;
    }

    return (
      <div className="user-card">
        <img className="user-avatar" src={user.avatar_url} alt={user.login} />
        <div className="user-info">
          <div>{user.name}</div>
          <div>{user.login}</div>
          <div>{user.bio}</div>
        </div>
      </div>
    );
  }
}

export default App;
总结

在本教程中,我们使用 React 和 Github API 来构建了一个简单的应用程序。我们首先生成了一个 Github API 的 Access Token,然后使用 Create React App 创建了一个新的 React 应用程序。我们使用 fetch 函数从 Github API 请求用户数据,并在组件状态中保存该用户数据。最后,我们在组件的 render 函数中使用该数据来显示用户数据。