如何将 React 中的 REST API 与 fetch 和 Axios 集成

来源:undefined 2025-01-20 02:21:56 1029

在 React 应用中集成 REST API

将 REST API 集成到 React 应用是前端开发的常见需求。REST (Representational State Transfer) 是一种架构风格,允许通过 HTTP 方法 (GET, POST, PUT, DELETE 等) 与外部资源 (数据) 交互。React 可以轻松地与 REST API 集成,实现高效的数据获取、新增、更新和删除操作。

本文将介绍如何使用 fetch API 和 Axios 等方法在 React 应用中集成 REST API,并处理异步数据获取。

1. 从 REST API 获取数据

JavaScript 内置的 fetch() 函数提供了一种简单的发出 HTTP 请求的方法。它返回一个 Promise,该 Promise 解析为包含请求响应的 Response 对象。

使用 fetch API 获取数据

以下示例演示如何使用 fetch API 从 REST API 获取数据并在 React 组件中显示:

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

import React, { useState, useEffect } from react;

const apiUrl = https://jsonplaceholder.typicode.com/posts; // 示例 REST API

const FetchPosts = () => {

const [posts, setPosts] = useState([]);

const [loading, setLoading] = useState(true);

const [error, setError] = useState(null);

useEffect(() => {

// 从 API 获取数据

fetch(apiUrl)

.then(response => {

if (!response.ok) {

throw new Error(网络响应不正常);

}

return response.json();

})

.then(data => {

setPosts(data);

setLoading(false);

})

.catch(error => {

setError(error.message);

setLoading(false);

});

}, []);

if (loading) return <div>加载中...</div>;

if (error) return <div>错误: {error}</div>;

return (

<div>

<h1>文章列表</h1>

<ul>

{posts.map(post => (

<li key={post.id}>

<h2>{post.title}</h2>

<p>{post.body}</p>

</li>

))}

</ul>

</div>

);

};

export default FetchPosts;

登录后复制
useState: 用于存储文章数据、加载状态和错误信息。 useEffect: 在组件挂载时处理数据获取。 fetch(): 从 REST API 端点获取数据,并将其解析为 JSON 格式。 错误处理: 捕获网络错误等异常,并设置错误状态。

2. 使用 Axios 进行 API 请求

Axios 是一个基于 Promise 的 HTTP 客户端,适用于浏览器和 Node.js。它提供比 fetch 更简洁的语法,并支持自动 JSON 转换、请求取消等附加功能。

安装 Axios

使用 npm 安装 Axios:

1

npm install axios

登录后复制
使用 Axios 获取数据

以下示例与上一个示例相同,但使用 Axios:

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

import React, { useState, useEffect } from react;

import axios from axios;

const apiUrl = https://jsonplaceholder.typicode.com/posts;

const FetchPostsAxios = () => {

const [posts, setPosts] = useState([]);

const [loading, setLoading] = useState(true);

const [error, setError] = useState(null);

useEffect(() => {

// 使用 Axios 从 API 获取数据

axios.get(apiUrl)

.then(response => {

setPosts(response.data);

setLoading(false);

})

.catch(error => {

setError(error.message);

setLoading(false);

});

}, []);

if (loading) return <div>加载中...</div>;

if (error) return <div>错误: {error}</div>;

return (

<div>

<h1>文章列表</h1>

<ul>

{posts.map(post => (

<li key={post.id}>

<h2>{post.title}</h2>

<p>{post.body}</p>

</li>

))}

</ul>

</div>

);

};

export default FetchPostsAxios;

登录后复制
axios.get(): 从 REST API 获取数据。Axios 自动将响应解析为 JSON。 错误处理: 捕获并显示错误信息。

3. 向 REST API 发送数据 (POST 请求)

除了 GET 请求,还可以使用 POST 请求向服务器发送数据,通常用于提交表单或创建新记录。

使用 fetch 发送 POST 请求

1

2

3

4

5

6

import React, { useState } from react;

const postUrl = https://jsonplaceholder.typicode.com/posts;

const CreatePost = () => {

const [title, set

登录后复制

以上就是如何将 React 中的 REST API 与 fetch 和 Axios 集成的详细内容,更多请关注php中文网其它相关文章!

最新文章