syncfusion-react-progress-bar
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseImplementing React Progress Bar Component
实现React Progress Bar组件
A comprehensive skill for implementing the Syncfusion React Progress Bar component for visual progress feedback, loading states, and task completion indicators.
本技能全面讲解如何实现Syncfusion React Progress Bar组件,用于展示进度视觉反馈、加载状态及任务完成指示器。
When to Use This Skill
何时使用此技能
Use this skill when you need to:
- Display progress of file uploads or downloads
- Show task completion percentage
- Indicate loading states (determinate or indeterminate)
- Visualize data processing or long-running operations
- Create progress spinners or circular indicators
- Handle secondary progress (buffer scenarios)
- Customize progress bar appearance and colors
- Implement animations and transitions
- Handle progress events and callbacks
- Ensure accessibility compliance for progress indicators
当你需要以下功能时使用本技能:
- 显示文件上传或下载的进度
- 展示任务完成百分比
- 指示加载状态(确定或不确定)
- 可视化数据处理或长时间运行的操作
- 创建进度旋转器或圆形指示器
- 处理次级进度(缓冲场景)
- 自定义进度条外观和颜色
- 实现动画和过渡效果
- 处理进度事件和回调函数
- 确保进度指示器符合无障碍访问规范
Component Overview
组件概述
The Syncfusion React Progress Bar is a lightweight component that visualizes task progress in linear, circular, or semi-circular shapes. It supports multiple states (determinate, indeterminate, buffer) and features animations, customization, and full accessibility support.
Key Features:
- Multiple Types: Linear, Circular, Semi-Circular shapes
- States: Determinate (known progress), Indeterminate (unknown), Buffer (secondary progress)
- Animations: Smooth transitions with configurable duration and delay
- Customization: Colors, heights, labels, themes
- Events: Progress tracking, start/complete callbacks
- Accessibility: WCAG 2.1 compliant with ARIA support
- RTL Support: Right-to-left language support
Syncfusion React Progress Bar是一款轻量级组件,支持以线性、圆形或半圆形可视化任务进度。它支持多种状态(确定、不确定、缓冲),并具备动画、自定义和完整的无障碍支持功能。
核心特性:
- 多种类型: 线性、圆形、半圆形
- 状态: 确定(已知进度)、不确定(未知进度)、缓冲(次级进度)
- 动画: 可配置时长和延迟的平滑过渡
- 自定义: 颜色、高度、标签、主题
- 事件: 进度跟踪、开始/完成回调
- 无障碍: 符合WCAG 2.1标准,支持ARIA属性
- RTL支持: 从右到左的语言布局支持
Documentation Guide
文档指南
Getting Started
快速入门
📄 Read: references/getting-started.md
- Installation and package setup
- Basic progress bar implementation
- CSS imports and themes
- First component example
- TypeScript vs JavaScript
📄 阅读: references/getting-started.md
- 安装和包配置
- 基础进度条实现
- CSS导入和主题
- 首个组件示例
- TypeScript与JavaScript对比
Types and Shapes
类型与形状
📄 Read: references/types-and-shapes.md
- Linear progress bar
- Circular progress bar
- Semi-circular progress bar
- Shape variations and code examples
- Choosing the right type for your use case
📄 阅读: references/types-and-shapes.md
- 线性进度条
- 圆形进度条
- 半圆形进度条
- 形状变体及代码示例
- 根据使用场景选择合适的类型
States and Modes
状态与模式
📄 Read: references/states-and-modes.md
- Determinate state (known progress, default)
- Indeterminate state (unknown progress, spinners)
- Buffer/Secondary progress (dual progress indicators)
- Combining multiple states
- Real-world scenarios for each state
📄 阅读: references/states-and-modes.md
- 确定状态(已知进度,默认)
- 不确定状态(未知进度,旋转器)
- 缓冲/次级进度(双进度指示器)
- 组合多种状态
- 每种状态的实际应用场景
Customization and Styling
自定义与样式
📄 Read: references/customization-and-styling.md
- Sizing (height, width configurations)
- Colors and fill customization
- Labels and text display
- Theme application
- CSS customization
- Responsive design patterns
📄 阅读: references/customization-and-styling.md
- 尺寸(高度、宽度配置)
- 颜色和填充自定义
- 标签和文本显示
- 主题应用
- CSS自定义
- 响应式设计模式
Animations, Events, and Accessibility
动画、事件与无障碍
📄 Read: references/animations-events-accessibility.md
- Animation configuration and control
- Event handlers for progress tracking
- Using callbacks for task completion
- WCAG compliance
- ARIA attributes and labels
- Tooltip and annotation support
- Troubleshooting common issues
📄 阅读: references/animations-events-accessibility.md
- 动画配置与控制
- 进度跟踪的事件处理器
- 使用回调函数处理任务完成
- WCAG合规性
- ARIA属性和标签
- 工具提示和注释支持
- 常见问题排查
API Reference
API参考
📄 Read: references/api.md
- Full list of public properties, methods and events for (see file).
ProgressBarComponent
📄 阅读: references/api.md
- 的完整公共属性、方法和事件列表(详见文件)。
ProgressBarComponent
Quick Start Example
快速开始示例
tsx
import { ProgressBarComponent } from '@syncfusion/ej2-react-progressbar';
function App() {
return (
<div>
{/* Linear Determinate Progress Bar */}
<ProgressBarComponent
id="linear"
type="Linear"
height="60"
value={75}
animation={{
enable: true,
duration: 2000,
delay: 0
}}
/>
{/* Circular Progress Bar */}
<ProgressBarComponent
id="circular"
type="Circular"
height="160px"
value={60}
/>
{/* Indeterminate Loading Spinner */}
<ProgressBarComponent
id="indeterminate"
type="Linear"
height="60"
isIndeterminate={true}
animation={{
enable: true,
duration: 2000,
delay: 0
}}
/>
</div>
);
}
export default App;tsx
import { ProgressBarComponent } from '@syncfusion/ej2-react-progressbar';
function App() {
return (
<div>
{/* 线性确定进度条 */}
<ProgressBarComponent
id="linear"
type="Linear"
height="60"
value={75}
animation={{
enable: true,
duration: 2000,
delay: 0
}}
/>
{/* 圆形进度条 */}
<ProgressBarComponent
id="circular"
type="Circular"
height="160px"
value={60}
/>
{/* 不确定加载旋转器 */}
<ProgressBarComponent
id="indeterminate"
type="Linear"
height="60"
isIndeterminate={true}
animation={{
enable: true,
duration: 2000,
delay: 0
}}
/>
</div>
);
}
export default App;Common Patterns
常见模式
1. File Upload Progress
1. 文件上传进度
tsx
<ProgressBarComponent
id="upload"
type="Linear"
value={uploadPercentage}
showProgressValue={true}
progressValueFormat="N0 '%'"
/>tsx
<ProgressBarComponent
id="upload"
type="Linear"
value={uploadPercentage}
showProgressValue={true}
progressValueFormat="N0 '%'"
/>2. Loading Spinner
2. 加载旋转器
tsx
<ProgressBarComponent
id="spinner"
type="Circular"
isIndeterminate={true}
height="100px"
/>tsx
<ProgressBarComponent
id="spinner"
type="Circular"
isIndeterminate={true}
height="100px"
/>3. Buffer Progress (Buffered Loading)
3. 缓冲进度(缓冲加载)
tsx
<ProgressBarComponent
id="buffer"
type="Linear"
value={40}
secondaryProgress={80}
height="60"
/>tsx
<ProgressBarComponent
id="buffer"
type="Linear"
value={40}
secondaryProgress={80}
height="60"
/>4. Determinate Task Progress
4. 确定任务进度
tsx
<ProgressBarComponent
id="task"
type="Linear"
value={taskCompletionPercentage}
showProgressValue={true}
animation={{
enable: true,
duration: 1500
}}
/>tsx
<ProgressBarComponent
id="task"
type="Linear"
value={taskCompletionPercentage}
showProgressValue={true}
animation={{
enable: true,
duration: 1500
}}
/>Key Props Reference
核心属性参考
Core Properties
核心属性
| Prop | Type | Default | Purpose |
|---|---|---|---|
| string | - | Unique identifier for component |
| "Linear" | "Circular" | "Semicircle" | "Linear" | Shape of progress bar |
| number | 0 | Current progress value (0-100) |
| number | 0 | Secondary/buffer progress value |
| boolean | false | Indeterminate/loading mode |
| string | "100%" | Height of progress bar (CSS value) |
| string | "100%" | Width of progress bar (CSS value) |
| boolean | false | Display percentage text |
| 属性 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| string | - | 组件的唯一标识符 |
| "Linear" | "Circular" | "Semicircle" | "Linear" | 进度条的形状 |
| number | 0 | 当前进度值(0-100) |
| number | 0 | 次级/缓冲进度值 |
| boolean | false | 不确定/加载模式 |
| string | "100%" | 进度条高度(CSS值) |
| string | "100%" | 进度条宽度(CSS值) |
| boolean | false | 显示百分比文本 |
Animation & Styling
动画与样式
| Prop | Type | Default | Purpose |
|---|---|---|---|
| AnimationModel | - | Animation config: |
| string | - | Color for progress fill (CSS color) |
| string | - | Color for track background |
| number | 4 | Progress bar thickness (pixels) |
| number | 4 | Track thickness (pixels) |
| boolean | false | Striped pattern appearance |
| boolean | false | Gradient fill effect |
| string | - | Custom CSS class for styling |
| 属性 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| AnimationModel | - | 动画配置: |
| string | - | 进度填充颜色(CSS颜色) |
| string | - | 轨道背景颜色 |
| number | 4 | 进度条厚度(像素) |
| number | 4 | 轨道厚度(像素) |
| boolean | false | 条纹图案外观 |
| boolean | false | 渐变填充效果 |
| string | - | 自定义样式的CSS类 |
Advanced Features
高级特性
| Prop | Type | Default | Purpose |
|---|---|---|---|
| "Round" | "Auto" | "Auto" | Corner style for ends |
| boolean | false | Right-to-left layout |
| boolean | false | Pie view for circular type |
| boolean | false | Segmented progress rendering |
| number | 1 | Number of segments |
| RangeColorModel[] | - | Colors for different ranges |
| number | 0 | Minimum progress value |
| number | 100 | Maximum progress value |
| 属性 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| "Round" | "Auto" | "Auto" | 两端的边角样式 |
| boolean | false | 从右到左布局 |
| boolean | false | 圆形进度条的饼图视图 |
| boolean | false | 分段进度渲染 |
| number | 1 | 分段数量 |
| RangeColorModel[] | - | 不同范围的颜色 |
| number | 0 | 最小进度值 |
| number | 100 | 最大进度值 |
Label & Format
标签与格式
| Prop | Type | Default | Purpose |
|---|---|---|---|
| string | "N0 '%'" | Format for value display (e.g., "N2 '%'") |
| boolean | true | Show label on the track |
| FontModel | - | Font styling for label |
When to use each:
- type: Choose based on space: Linear (full-width), Circular/Semicircle (compact)
- value: Update via state to reflect real progress
- isIndeterminate: Use for unknown duration tasks (loading, processing)
- secondaryProgress: Show buffer/estimated vs. actual progress
- animation: Enhance UX with smooth transitions (disable for real-time high-frequency updates)
- cornerRadius: "Round" for modern look, "Auto" for default
- segmentCount: Split progress into visual segments (e.g., 10 segments = 10% per segment)
| 属性 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| string | "N0 '%'" | 值显示格式(例如:"N2 '%'") |
| boolean | true | 在轨道上显示标签 |
| FontModel | - | 标签的字体样式 |
各属性的使用场景:
- type:根据空间选择:Linear(全宽)、Circular/Semicircle(紧凑)
- value:通过状态更新以反映实时进度
- isIndeterminate:用于未知时长的任务(加载、处理)
- secondaryProgress:显示缓冲/预估与实际进度
- animation:通过平滑过渡提升用户体验(实时高频更新时禁用)
- cornerRadius:"Round"用于现代外观,"Auto"为默认样式
- segmentCount:将进度拆分为可视化分段(例如:10个分段=每个分段10%)
Common Use Cases with Code Examples
常见使用场景及代码示例
Use Case 1: File Upload/Download
场景1:文件上传/下载
tsx
const [uploadProgress, setUploadProgress] = useState(0);
<ProgressBarComponent
type="Linear"
value={uploadProgress}
showProgressValue={true}
progressValueFormat="N0 '%'"
height="30"
animation={{ enable: true, duration: 500 }}
/>Best Practices:
- Use Linear type for wide displays
- Update value from upload progress events
- Show estimated time in addition to percentage
- Optional for pre-fetched bytes
secondaryProgress
tsx
const [uploadProgress, setUploadProgress] = useState(0);
<ProgressBarComponent
type="Linear"
value={uploadProgress}
showProgressValue={true}
progressValueFormat="N0 '%'"
height="30"
animation={{ enable: true, duration: 500 }}
/>最佳实践:
- 在宽屏显示中使用Linear类型
- 通过上传进度事件更新value值
- 除百分比外显示预估时间
- 可选使用显示预获取字节数
secondaryProgress
Use Case 2: Loading State (Unknown Duration)
场景2:加载状态(未知时长)
tsx
<ProgressBarComponent
type="Circular"
isIndeterminate={true}
height="100px"
animation={{ enable: true, duration: 2000 }}
/>Best Practices:
- Use Circular for compact display
- Keep until operation completes
isIndeterminate={true} - Spinner continues animating indefinitely
- Replace with determinate once progress can be tracked
tsx
<ProgressBarComponent
type="Circular"
isIndeterminate={true}
height="100px"
animation={{ enable: true, duration: 2000 }}
/>最佳实践:
- 在紧凑显示中使用Circular类型
- 保持直到操作完成
isIndeterminate={true} - 旋转器持续动画
- 可跟踪进度后替换为确定状态
Use Case 3: Data Processing
场景3:数据处理
tsx
const [processProgress, setProcessProgress] = useState(0);
const totalItems = 100;
useEffect(() => {
processItems().then(processed => {
setProcessProgress((processed / totalItems) * 100);
});
}, []);
<ProgressBarComponent
type="Linear"
value={processProgress}
showProgressValue={true}
height="30"
/>Best Practices:
- Update value as items are processed
- Show item count: "25 of 100 items"
- Show elapsed time and estimated remaining
- Display success/error message on completion
tsx
const [processProgress, setProcessProgress] = useState(0);
const totalItems = 100;
useEffect(() => {
processItems().then(processed => {
setProcessProgress((processed / totalItems) * 100);
});
}, []);
<ProgressBarComponent
type="Linear"
value={processProgress}
showProgressValue={true}
height="30"
/>最佳实践:
- 处理项目时更新value值
- 显示项目数量:"已处理25/100个项目"
- 显示已用时间和预估剩余时间
- 完成时显示成功/错误消息
Use Case 4: Multiple Tasks (Buffering/Streaming)
场景4:多任务(缓冲/流式传输)
tsx
const [processedItems, setProcessedItems] = useState(30);
const [queuedItems, setQueuedItems] = useState(75);
const totalItems = 100;
<ProgressBarComponent
type="Linear"
value={(processedItems / totalItems) * 100}
secondaryProgress={(queuedItems / totalItems) * 100}
height="30"
/>Best Practices:
- Primary progress (value) = actual processed
- Secondary progress = queued/buffered items
- Great for streaming/video buffering scenarios
- Also works for task queue management
tsx
const [processedItems, setProcessedItems] = useState(30);
const [queuedItems, setQueuedItems] = useState(75);
const totalItems = 100;
<ProgressBarComponent
type="Linear"
value={(processedItems / totalItems) * 100}
secondaryProgress={(queuedItems / totalItems) * 100}
height="30"
/>最佳实践:
- 主进度(value)= 实际已处理进度
- 次级进度 = 已排队/已缓冲项目
- 非常适合流式传输/视频缓冲场景
- 也适用于任务队列管理
Use Case 5: Multi-Step Workflow
场景5:多步骤工作流
tsx
const steps = ['Validation', 'Processing', 'Upload', 'Confirmation'];
const [currentStep, setCurrentStep] = useState(0);
const progress = ((currentStep + 1) / steps.length) * 100;
<ProgressBarComponent
type="Linear"
value={progress}
showProgressValue={true}
height="30"
/>
<div>
{steps.map((step, i) => (
<div key={i}>
{step} {i === currentStep ? '🔄' : i < currentStep ? '✓' : '⏳'}
</div>
))}
</div>Best Practices:
- Calculate progress as (currentStep / totalSteps) * 100
- Show step indicators alongside progress bar
- Highlight current step
- Disable user interactions during processing
tsx
const steps = ['验证', '处理', '上传', '确认'];
const [currentStep, setCurrentStep] = useState(0);
const progress = ((currentStep + 1) / steps.length) * 100;
<ProgressBarComponent
type="Linear"
value={progress}
showProgressValue={true}
height="30"
/>
<div>
{steps.map((step, i) => (
<div key={i}>
{step} {i === currentStep ? '🔄' : i < currentStep ? '✓' : '⏳'}
</div>
))}
</div>最佳实践:
- 进度计算公式:(currentStep / totalSteps) * 100
- 在进度条旁显示步骤指示器
- 高亮当前步骤
- 处理期间禁用用户交互
Advanced Usage Patterns
高级使用模式
1. Value Binding with State Management
1. 状态管理的值绑定
tsx
import { useState, useEffect } from 'react';
import { ProgressBarComponent } from '@syncfusion/ej2-react-progressbar';
function ProgressManager() {
const [progress, setProgress] = useState(0);
const [isProcessing, setIsProcessing] = useState(false);
useEffect(() => {
if (!isProcessing) return;
const interval = setInterval(() => {
setProgress(prev => {
if (prev >= 100) {
setIsProcessing(false);
return 100;
}
return prev + Math.random() * 15;
});
}, 500);
return () => clearInterval(interval);
}, [isProcessing]);
return (
<div>
<ProgressBarComponent
type="Linear"
value={progress}
showProgressValue={true}
/>
<button
onClick={() => { setProgress(0); setIsProcessing(true); }}
disabled={isProcessing}
>
{isProcessing ? 'Processing...' : 'Start'}
</button>
</div>
);
}
export default ProgressManager;tsx
import { useState, useEffect } from 'react';
import { ProgressBarComponent } from '@syncfusion/ej2-react-progressbar';
function ProgressManager() {
const [progress, setProgress] = useState(0);
const [isProcessing, setIsProcessing] = useState(false);
useEffect(() => {
if (!isProcessing) return;
const interval = setInterval(() => {
setProgress(prev => {
if (prev >= 100) {
setIsProcessing(false);
return 100;
}
return prev + Math.random() * 15;
});
}, 500);
return () => clearInterval(interval);
}, [isProcessing]);
return (
<div>
<ProgressBarComponent
type="Linear"
value={progress}
showProgressValue={true}
/>
<button
onClick={() => { setProgress(0); setIsProcessing(true); }}
disabled={isProcessing}
>
{isProcessing ? '处理中...' : '开始'}
</button>
</div>
);
}
export default ProgressManager;2. Animation Configuration Patterns
2. 动画配置模式
tsx
// Real-time updates (no animation for smoothness)
animation={{ enable: false }}
// User interactions (quick feedback)
animation={{ enable: true, duration: 300, delay: 0 }}
// Page loads (smooth transition)
animation={{ enable: true, duration: 1500, delay: 0 }}
// Cascading effects (staggered)
animation={{ enable: true, duration: 1000, delay: 200 }}
// Loading spinners (continuous)
animation={{ enable: true, duration: 2000 }}tsx
// 实时更新(禁用动画以保证流畅性)
animation={{ enable: false }}
// 用户交互(快速反馈)
animation={{ enable: true, duration: 300, delay: 0 }}
// 页面加载(平滑过渡)
animation={{ enable: true, duration: 1500, delay: 0 }}
// 级联效果(交错动画)
animation={{ enable: true, duration: 1000, delay: 200 }}
// 加载旋转器(持续动画)
animation={{ enable: true, duration: 2000 }}3. Conditional Rendering Based on State
3. 基于状态的条件渲染
tsx
function ConditionalProgress() {
const [state, setState] = useState('idle'); // idle | loading | success | error
const [value, setValue] = useState(0);
const getProgressType = () => {
if (state === 'loading') return 'Circular';
return 'Linear';
};
return (
<>
{state === 'loading' && (
<ProgressBarComponent
type={getProgressType()}
isIndeterminate={state === 'loading'}
height="100px"
/>
)}
{state === 'success' && (
<div style={{ color: 'green' }}>✓ Complete</div>
)}
{state === 'error' && (
<div style={{ color: 'red' }}>✗ Error occurred</div>
)}
</>
);
}
export default ConditionalProgress;tsx
function ConditionalProgress() {
const [state, setState] = useState('idle'); // idle | loading | success | error
const [value, setValue] = useState(0);
const getProgressType = () => {
if (state === 'loading') return 'Circular';
return 'Linear';
};
return (
<>
{state === 'loading' && (
<ProgressBarComponent
type={getProgressType()}
isIndeterminate={state === 'loading'}
height="100px"
/>
)}
{state === 'success' && (
<div style={{ color: 'green' }}>✓ 完成</div>
)}
{state === 'error' && (
<div style={{ color: 'red' }}>✗ 发生错误</div>
)}
</>
);
}
export default ConditionalProgress;4. Event Handling for Tracking
4. 用于跟踪的事件处理
tsx
function ProgressWithEvents() {
const handleStart = () => {
console.log('Progress started');
analytics.track('progress_started');
};
const handleComplete = () => {
console.log('Progress completed');
analytics.track('progress_completed');
showNotification('Task completed!');
};
const handleValueChange = (args) => {
console.log(`Progress: ${args.value}%`);
// Milestone tracking
if (args.value === 50) {
analytics.track('progress_midpoint');
}
};
return (
<ProgressBarComponent
type="Linear"
value={75}
progressStart={handleStart}
progressComplete={handleComplete}
valueChanged={handleValueChange}
/>
);
}
export default ProgressWithEvents;tsx
function ProgressWithEvents() {
const handleStart = () => {
console.log('进度已开始');
analytics.track('progress_started');
};
const handleComplete = () => {
console.log('进度已完成');
analytics.track('progress_completed');
showNotification('任务已完成!');
};
const handleValueChange = (args) => {
console.log(`进度:${args.value}%`);
// 里程碑跟踪
if (args.value === 50) {
analytics.track('progress_midpoint');
}
};
return (
<ProgressBarComponent
type="Linear"
value={75}
progressStart={handleStart}
progressComplete={handleComplete}
valueChanged={handleValueChange}
/>
);
}
export default ProgressWithEvents;5. Responsive Design
5. 响应式设计
tsx
function ResponsiveProgress() {
const [isMobile, setIsMobile] = useState(window.innerWidth < 768);
useEffect(() => {
const handleResize = () => setIsMobile(window.innerWidth < 768);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return (
<ProgressBarComponent
type={isMobile ? 'Semicircle' : 'Linear'}
value={65}
height={isMobile ? '100px' : '40'}
showProgressValue={true}
/>
);
}
export default ResponsiveProgress;tsx
function ResponsiveProgress() {
const [isMobile, setIsMobile] = useState(window.innerWidth < 768);
useEffect(() => {
const handleResize = () => setIsMobile(window.innerWidth < 768);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return (
<ProgressBarComponent
type={isMobile ? 'Semicircle' : 'Linear'}
value={65}
height={isMobile ? '100px' : '40'}
showProgressValue={true}
/>
);
}
export default ResponsiveProgress;6. Error Handling & Retry Logic
6. 错误处理与重试逻辑
tsx
async function uploadWithRetry(file, maxRetries = 3) {
const [attempts, setAttempts] = useState(0);
const [progress, setProgress] = useState(0);
const [error, setError] = useState(null);
for (let i = 0; i < maxRetries; i++) {
try {
setAttempts(i + 1);
const result = await uploadFile(file, (p) => setProgress(p));
return result;
} catch (err) {
if (i === maxRetries - 1) {
setError(`Failed after ${maxRetries} attempts`);
throw err;
}
// Retry with exponential backoff
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
}
}
}tsx
async function uploadWithRetry(file, maxRetries = 3) {
const [attempts, setAttempts] = useState(0);
const [progress, setProgress] = useState(0);
const [error, setError] = useState(null);
for (let i = 0; i < maxRetries; i++) {
try {
setAttempts(i + 1);
const result = await uploadFile(file, (p) => setProgress(p));
return result;
} catch (err) {
if (i === maxRetries - 1) {
setError(`尝试${maxRetries}次后失败`);
throw err;
}
// 指数退避重试
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
}
}
}Integration with Common Patterns
与常见模式的集成
With React Query
与React Query集成
tsx
import { useQuery } from '@tanstack/react-query';
function DataProcessing() {
const { data, isLoading, progress } = useQuery({
queryKey: ['processData'],
queryFn: async ({ signal }) => {
// Process with progress tracking
}
});
return (
<ProgressBarComponent
isIndeterminate={isLoading}
value={progress || 0}
/>
);
}tsx
import { useQuery } from '@tanstack/react-query';
function DataProcessing() {
const { data, isLoading, progress } = useQuery({
queryKey: ['processData'],
queryFn: async ({ signal }) => {
// 带进度跟踪的处理逻辑
}
});
return (
<ProgressBarComponent
isIndeterminate={isLoading}
value={progress || 0}
/>
);
}With Redux
与Redux集成
tsx
import { useSelector, useDispatch } from 'react-redux';
function ReduxProgress() {
const { progress, isLoading } = useSelector(state => state.upload);
const dispatch = useDispatch();
return (
<ProgressBarComponent
value={progress}
isIndeterminate={isLoading}
progressComplete={() => dispatch(resetProgress())}
/>
);
}tsx
import { useSelector, useDispatch } from 'react-redux';
function ReduxProgress() {
const { progress, isLoading } = useSelector(state => state.upload);
const dispatch = useDispatch();
return (
<ProgressBarComponent
value={progress}
isIndeterminate={isLoading}
progressComplete={() => dispatch(resetProgress())}
/>
);
}