25 从零到上手学习 React 框架 - 第三方 API 集成

25 从零到上手学习 React 框架 - 第三方 API 集成

在本节中,我们将学习如何在一个 React 应用中集成第三方 API。我们将分步骤进行,最终创建一个可以显示数据的简单应用。

1. 创建 React 应用

首先,确保你已经安装了 Node.jsnpm。接着使用以下命令创建一个新的 React 应用:

1
2
npx create-react-app my-api-app
cd my-api-app

2. 安装 Axios

我们将使用 Axios 这个库来进行 API 请求。使用以下命令安装 Axios:

1
npm install axios

3. 选择一个第三方 API

为了演示,我们将使用 JSONPlaceholder 这个假数据 API。这个 API 提供了一些模拟的数据,方便进行测试。

4. 创建数据获取组件

接下来,我们将创建一个新的组件,用于获取并显示数据。首先,在 src 文件夹内创建一个新文件 MyDataComponent.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// src/MyDataComponent.js

import React, { useEffect, useState } from 'react';
import axios from 'axios';

const MyDataComponent = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
// 定义异步获取数据的函数
const fetchData = async () => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
setData(response.data); // 使用获取到的数据更新状态
} catch (err) {
setError(err); // 捕获错误
} finally {
setLoading(false); // 数据请求结束,设置加载状态为 false
}
};

fetchData(); // 调用获取数据的函数
}, []); // 空数组意味着只在组件挂载时运行

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

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

return (
<div>
<h1>Posts</h1>
<ul>
{data.map(post => (
<li key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
</li>
))}
</ul>
</div>
);
};

export default MyDataComponent;

组件详细解读

  • useEffect: 此钩子用于处理副作用,例如 API 请求。我们提供一个空依赖数组 [],表示仅在组件首次加载时执行。
  • axios.get(): 用于发送 GET 请求并获取数据。
  • 状态管理:使用 useState 来管理数据、加载状态和错误状态。
  • 条件渲染:根据不同状态返回不同的 JSX。

5. 在 App 组件中使用 MyDataComponent

接下来,将 MyDataComponent 导入并使用在 App.js 中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/App.js

import React from 'react';
import MyDataComponent from './MyDataComponent';

function App() {
return (
<div className="App">
<header className="App-header">
<h1>My API App</h1>
<MyDataComponent />
</header>
</div>
);
}

export default App;

6. 启动应用

现在,可以使用以下命令启动你的应用:

1
npm start

你的浏览器应该在 http://localhost:3000 打开,看到加载的 Posts 列表。

7. 总结

在本节中,我们学习了如何:

  • 创建 React 应用并安装 Axios。
  • 使用 Axios 与第三方 API 进行集成。
  • 管理组件的状态和副作用。
  • 实现简单的条件渲染。

使用第三方 API 扩展 React 应用的功能是非常强大且常见的实践。你可以尝试连接其他的 API,获取不同类型的数据并进行展示。

25 从零到上手学习 React 框架 - 第三方 API 集成

https://zglg.work/react-tutorial/25/

作者

AI教程网

发布于

2024-08-08

更新于

2024-08-10

许可协议