Hooks: useEffect
## 什麼是 React Hooks?
React Hooks 是 React 提供的一組函式,讓**函式元件(Function Component)** 可以使用狀態、生命週期與其他 React 功能,而不需要改寫成類別元件。
常見的 Hooks 包括:
- `useState`:管理元件狀態
- `useEffect`:處理副作用,例如取得後端資料、設定計時器
- `useContext`:取得 Context 資料
- `useRef`:保存 DOM 元素或不會觸發重新渲染的資料
- `useMemo`:快取計算結果
- `useCallback`:快取函式
### Hooks 使用規則
1. 只能在函式元件的最外層呼叫,不能放在 `if`、`for` 或巢狀函式中。
2. 只能在 React 函式元件或自訂 Hook 中呼叫。
---
## `useEffect` 的語法
```jsx
import { useEffect } from "react";
useEffect(() => {
// 副作用程式碼
return () => {
// 清除副作用,可省略
};
}, [依賴資料]);
```
`useEffect` 接受兩個參數:
### 第 1 個參數:副作用函式
這裡放需要在畫面渲染後執行的程式,例如:
- 呼叫後端 API
- 設定或清除計時器
- 訂閱事件
- 操作瀏覽器的 DOM
- 修改網頁標題
### 第 2 個參數:依賴陣列
```jsx
useEffect(() => {
// ...
}, []);
```
不同寫法的執行時機如下:
```jsx
// 元件每次重新渲染後都執行
useEffect(() => {
// ...
});
// 元件第一次顯示時執行一次
useEffect(() => {
// ...
}, []);
// 元件第一次顯示,以及 count 改變時執行
useEffect(() => {
// ...
}, [count]);
```
---
## 使用 `useEffect` 串接後端資料
以下範例會從指定的後端網址取得商品資料,並顯示商品名稱與價格。
```jsx
import { useEffect, useState } from "react";
function ProductList() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
async function fetchProducts() {
try {
setLoading(true);
const response = await fetch(
"https://cwpeng.github.io/live-records-samples/data/products.json",
{
signal: controller.signal,
}
);
if (!response.ok) {
throw new Error("取得商品資料失敗");
}
const data = await response.json();
setProducts(data);
} catch (error) {
// 元件卸載時取消請求,不需要顯示錯誤
if (error.name !== "AbortError") {
setError(error.message);
}
} finally {
setLoading(false);
}
}
fetchProducts();
// 元件卸載時取消尚未完成的請求
return () => {
controller.abort();
};
}, []);
if (loading) {
return <p>資料載入中...</p>;
}
if (error) {
return <p>錯誤:{error}</p>;
}
return (
<div>
<h2>商品列表</h2>
{products.map((product) => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>價格:{product.price}</p>
</div>
))}
</div>
);
}
export default ProductList;
```
### 範例說明
```jsx
useEffect(() => {
fetchProducts();
}, []);
```
由於依賴陣列是空陣列 `[]`,因此元件第一次顯示時會執行一次 `fetchProducts()`,向後端取得資料。
取得資料後:
```jsx
const data = await response.json();
setProducts(data);
```
`setProducts(data)` 會更新狀態,React 會重新渲染元件,將商品資料顯示在畫面上。
另外,`fetch` 是非同步操作,因此通常不直接將 `useEffect` 寫成 `async`:
```jsx
// 不建議
useEffect(async () => {
// ...
}, []);
```
比較常見且正確的方式,是在 `useEffect` 內宣告一個非同步函式,再呼叫它。
相關學習地圖、教學課程
F2E 網站前端工程