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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| 1、背景:假设原有代码是传统 Redux:
// actions.ts export const FETCH_USERS = 'FETCH_USERS'; export const fetchUsers = () => ({ type: FETCH_USERS });
// reducer.ts function userReducer(state = initialState, action) { switch (action.type) { case FETCH_USERS: return { ...state, loading: true }; ... } }
2、重构目标: -简化 action + reducer 编写; -支持类型推导; -支持异步请求处理; -提高模块内聚性;
3、重构步骤(RTK 实现):使用 createSlice + createAsyncThunk:
interface User { id: string; name: string; }
interface UserState { list: User[]; loading: boolean; error?: string; }
const initialState: UserState = { list: [], loading: false, };
export const fetchUsers = createAsyncThunk('users/fetch', async () => { const res = await fetch('/api/users'); return await res.json(); });
const userSlice = createSlice({ name: 'users', initialState, reducers: {}, extraReducers: builder => { builder .addCase(fetchUsers.pending, (state) => { state.loading = true }) .addCase(fetchUsers.fulfilled, (state, action) => { state.list = action.payload; state.loading = false; }) .addCase(fetchUsers.rejected, (state, action) => { state.error = action.error.message; state.loading = false; }); } });
|