文章

與 API 交互

與 API 交互

在 React 懠用中,與外部 API 的交互是很常見的需求。這通常涉及到發送 HTTP 請求來獲取或提交數據。以下將介紹如何使用 React 來與 API 進行交互,常見的方式包括使用 fetch API 和第三方庫如 axios


1. 使用 Fetch API

1.1 基本使用

fetch 是一個原生的 JavaScript 函數,用於發送網絡請求。它返回一個 Promise,當請求成功時,Promise 將解析為 Response 對象。

1
2
3
4
5
6
7
8
9
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json(); // 將 response 轉換為 JSON
  })
  .then(data => console.log(data))
  .catch(error => console.error('Fetch error:', error));

1.2 在 React 中使用 Fetch

在 React 中,通常在組件的 useEffect 中發送請求,以便在組件掛載時獲取數據。

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
import React, { useEffect, useState } from 'react';

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

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then(data => {
        setData(data);
        setLoading(false);
      })
      .catch(error => {
        setError(error);
        setLoading(false);
      });
  }, []); // 空依賴陣列表示只在組件掛載時執行

  if (loading) return <p>加載中...</p>;
  if (error) return <p>錯誤: {error.message}</p>;

  return (
    <div>
      <h1>數據:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default DataFetchingComponent;

1.3 請求方法

使用 fetch 進行其他類型的請求(例如 POST)可以通過傳遞一個配置對象來實現:

1
2
3
4
5
6
7
8
9
10
fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ key: 'value' }), // 將數據轉換為 JSON 字符串
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Fetch error:', error));

2. 使用 Axios

axios 是一個流行的第三方庫,提供了更簡單的 API 和一些額外的功能,例如請求和響應攔截器。

2.1 安裝 Axios

在你的 React 項目中安裝 axios

1
npm install axios

2.2 基本用法

以下是使用 axios 進行 GET 和 POST 請求的示例:

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
import React, { useEffect, useState } from 'react';
import axios from 'axios';

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

  useEffect(() => {
    axios.get('https://api.example.com/data')
      .then(response => {
        setData(response.data);
        setLoading(false);
      })
      .catch(error => {
        setError(error);
        setLoading(false);
      });
  }, []);

  if (loading) return <p>加載中...</p>;
  if (error) return <p>錯誤: {error.message}</p>;

  return (
    <div>
      <h1>數據:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default DataFetchingComponent;

2.3 發送 POST 請求

1
2
3
4
5
6
7
8
9
const handleSubmit = (data) => {
  axios.post('https://api.example.com/data', data)
    .then(response => {
      console.log('數據已發送:', response.data);
    })
    .catch(error => {
      console.error('發送錯誤:', error);
    });
};

3. 錯誤處理與請求攔截器

3.1 錯誤處理

不論使用 fetch 還是 axios,都應對錯誤進行適當處理。可以在 .catch 中捕獲錯誤,並在 UI 中顯示相應的錯誤信息。

3.2 使用請求攔截器

axios 提供了請求和響應攔截器,可以在發送請求之前或接收響應之後進行一些操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
axios.interceptors.request.use(request => {
  // 在發送請求之前做些事情
  console.log('請求發送:', request);
  return request;
}, error => {
  // 處理請求錯誤
  return Promise.reject(error);
});

axios.interceptors.response.use(response => {
  // 對響應數據做些事情
  return response;
}, error => {
  // 處理響應錯誤
  return Promise.reject(error);
});

4. 總結

  • Fetch API 是一個原生的 HTTP 請求工具,適合簡單的請求需求,但錯誤處理和請求設置較為繁瑣。
  • Axios 提供了更簡單和功能更強大的 API,特別適合複雜的請求和響應處理。
  • 無論使用哪種方法,良好的錯誤處理和狀態管理都是至關重要的,以提高用戶體驗。

通過這些技術,你可以在 React 應用中輕鬆與外部 API 進行交互,獲取和提交數據。

本文章以 CC BY 4.0 授權