Zustand 中处理异步操作的方法:
-
基本异步操作
- 在 store 中定义异步 action
- 使用 async/await 语法
- 示例:
javascript
import { create } from 'zustand'; const useUserStore = create((set) => ({ user: null, isLoading: false, error: null, fetchUser: async (userId) => { set({ isLoading: true, error: null }); try { const response = await fetch(`https://api.example.com/users/${userId}`); const user = await response.json(); set({ user, isLoading: false }); } catch (error) { set({ error: error.message, isLoading: false }); } }, }));
-
使用 Promise
- 返回 Promise 以便组件可以等待操作完成
- 示例:
javascript
fetchUser: async (userId) => { set({ isLoading: true, error: null }); try { const response = await fetch(`https://api.example.com/users/${userId}`); const user = await response.json(); set({ user, isLoading: false }); return user; // 返回结果 } catch (error) { set({ error: error.message, isLoading: false }); throw error; // 抛出错误 } },
-
处理多个异步操作
- 并行执行多个异步操作
- 示例:
javascript
fetchMultipleData: async () => { set({ isLoading: true }); try { const [user, posts] = await Promise.all([ fetch('https://api.example.com/user').then(res => res.json()), fetch('https://api.example.com/posts').then(res => res.json()) ]); set({ user, posts, isLoading: false }); } catch (error) { set({ error: error.message, isLoading: false }); } },
-
中间件处理
- 使用自定义中间件处理异步操作
- 示例:
javascript
const asyncMiddleware = (store) => (next) => (action) => { if (typeof action === 'function') { return action(store.getState, store.setState); } return next(action); }; const useStore = create( asyncMiddleware((set, get) => ({ // 状态和操作 })) );
-
最佳实践
- 始终处理加载状态和错误状态
- 为异步操作提供取消机制
- 合理使用 try/catch 捕获错误
- 考虑使用 SWR 或 React Query 处理复杂的异步数据
-
常见异步场景
- API 调用
- 数据加载和缓存
- 文件上传下载
- 认证和授权操作