1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| 推荐结构(中大型项目): 1、为每个模块设置 loading / error 字段: initialState: { data: [], loading: false, error: null }
2、在 createAsyncThunk 中封装错误处理: export const fetchSomething = createAsyncThunk( 'data/fetch', async (_, { rejectWithValue }) => { try { const res = await fetch(...); if (!res.ok) throw new Error('网络异常'); return await res.json(); } catch (e) { return rejectWithValue(e.message); } } );
3、在 reducer 中使用 action.payload 统一存错: .addCase(fetchSomething.rejected, (state, action) => { state.error = action.payload; });
4、UI 层根据 error 显示 toast / 报错弹窗。
|