如何在 Zustand 中处理异步操作?
Zustand 中处理异步操作的方法:基本异步操作在 store 中定义异步 action使用 async/await 语法示例: 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 }); } },中间件处理使用自定义中间件处理异步操作示例: 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 调用数据加载和缓存文件上传下载认证和授权操作