React UI 模式 是做什麼的?
核心原則
- 永不顯示過時 UI - 僅在實際載入時顯示載入旋轉圖示
- 始終呈現錯誤 - 使用者必須知道何時發生錯誤
- 樂觀更新 - 讓 UI 感覺即時
- 漸進式揭露 - 內容隨著可用性逐步顯示
- 優雅降級 - 部分資料總比沒有資料好
載入狀態模式
黃金法則
僅在沒有資料可顯示時才顯示載入指示器。
// 正確 - 僅在沒有資料時顯示載入
const { data, loading, error } = useGetItemsQuery();
if (error) return <ErrorState error={error} onRetry={refetch} />;
if (loading && !data) return <LoadingState />;
if (!data?.items.length) return <EmptyState />;
return <ItemList items={data.items} />;
// 錯誤 - 即使有快取資料也顯示旋轉圖示
if (loading) return <LoadingState />; // 重新擷取時會閃爍!
載入狀態決策樹
是否有錯誤?
→ 是:顯示帶有重試選項的錯誤狀態
→ 否:繼續
是否正在載入且我們沒有資料?
→ 是:顯示載入指示器(旋轉圖示/骨架螢幕)
→ 否:繼續
我們是否有資料?
→ 有,且有項目:顯示資料
→ 有,但為空:顯示空狀態
→ 沒有:顯示載入(備用)
骨架螢幕與旋轉圖示
| 使用骨架螢幕時機 | 使用旋轉圖示時機 |
|---|---|
| 已知內容形狀 | 未知內容形狀 |
| 列表/卡片佈局 | 模態框操作 |
| 初始頁面載入 | 按鈕提交 |
| 內容佔位符 | 內聯操作 |
錯誤處理模式
錯誤處理層級
1. 內聯錯誤(欄位層級)→ 表單驗證錯誤
2. Toast 通知 → 可復原錯誤,使用者可以重試
3. 錯誤橫幅 → 頁面層級錯誤,資料仍可部分使用
4. 完整錯誤畫面 → 不可復原,需要使用者操作
始終顯示錯誤
重要:切勿靜默吞沒錯誤。
// 正確 - 錯誤始終呈現給使用者
const [createItem, { loading }] = useCreateItemMutation({
onCompleted: () => {
toast.success({ title: '項目已建立' });
},
onError: (error) => {
console.error('createItem 失敗:', error);
toast.error({ title: '建立項目失敗' });
},
});
// 錯誤 - 錯誤被靜默捕獲,使用者完全不知道
const [createItem] = useCreateItemMutation({
onError: (error) => {
console.error(error); // 使用者看不到任何東西!
},
});
錯誤狀態元件模式
interface ErrorStateProps {
error: Error;
onRetry?: () => void;
title?: string;
}
const ErrorState = ({ error, onRetry, title }: ErrorStateProps) => (
<div className="error-state">
<Icon name="exclamation-circle" />
<h3>{title ?? '發生錯誤'}</h3>
<p>{error.message}</p>
{onRetry && (
<Button onClick={onRetry}>重試</Button>
)}
</div>
);
按鈕狀態模式
按鈕載入狀態
<Button
onClick={handleSubmit}
isLoading={isSubmitting}
disabled={!isValid || isSubmitting}
>
提交
</Button>
操作期間停用
重要:非同步操作期間務必停用觸發器。
// 正確 - 載入時按鈕被停用
<Button
disabled={isSubmitting}
isLoading={isSubmitting}
onClick={handleSubmit}
>
提交
</Button>
// 錯誤 - 使用者可以點擊多次
<Button onClick={handleSubmit}>
{isSubmitting ? '提交中...' : '提交'}
</Button>
空狀態
空狀態需求
每個列表/集合都必須有空狀態:
// 錯誤 - 沒有空狀態
return <FlatList data={items} />;
// 正確 - 明確的空狀態
return (
<FlatList
data={items}
ListEmptyComponent={<EmptyState />}
/>
);
情境式空狀態
// 搜尋無結果
<EmptyState
icon="search"
title="找不到結果"
description="嘗試不同的搜尋詞"
/>
// 列表尚無項目
<EmptyState
icon="plus-circle"
title="尚無項目"
description="建立您的第一個項目"
action={{ label: '建立項目', onClick: handleCreate }}
/>
表單提交模式
const MyForm = () => {
const [submit, { loading }] = useSubmitMutation({
onCompleted: handleSuccess,
onError: handleError,
});
const handleSubmit = async () => {
if (!isValid) {
toast.error({ title: '請修正錯誤' });
return;
}
await submit({ variables: { input: values } });
};
return (
<form>
<Input
value={values.name}
onChange={handleChange('name')}
error={touched.name ? errors.name : undefined}
/>
<Button
type="submit"
onClick={handleSubmit}
disabled={!isValid || loading}
isLoading={loading}
>
提交
</Button>
</form>
);
};
反模式
載入狀態
// 錯誤 - 資料存在時顯示旋轉圖示(導致閃爍)
if (loading) return <Spinner />;
// 正確 - 僅在沒有資料時顯示載入
if (loading && !data) return <Spinner />;
錯誤處理
// 錯誤 - 錯誤被吞沒
try {
await mutation();
} catch (e) {
console.log(e); // 使用者完全不知道!
}
// 正確 - 錯誤被呈現
onError: (error) => {
console.error('操作失敗:', error);
toast.error({ title: '操作失敗' });
}
按鈕狀態
// 錯誤 - 提交期間按鈕未停用
<Button onClick={submit}>提交</Button>
// 正確 - 停用並顯示載入狀態
<Button onClick={submit} disabled={loading} isLoading={loading}>
提交
</Button>
檢查清單
在完成任何 UI 元件之前:
UI 狀態:
- 錯誤狀態已處理並呈現給使用者
- 僅在沒有資料時顯示載入狀態
- 集合已提供空狀態
- 非同步操作期間按鈕已停用
- 按鈕在適當情況下顯示載入指示器
資料與變更:
- 變更有 onError 處理器
- 所有使用者操作都有回饋(toast/視覺)
與其他技能的整合
- graphql-schema:使用帶有適當錯誤處理的變更模式
- testing-patterns:測試所有 UI 狀態(載入、錯誤、空、成功)
- formik-patterns:套用表單提交模式