一、 创建异步函数
javascript
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { getStuListApi } from '../api/stuApi';
// 1. 创建异步 thunk
const fetchStudents = createAsyncThunk(
'students/fetchStudents',
async () => {
const response = await getStuListApi();
return response;
}
);
// 2. 创建 slice
const studentsSlice = createSlice({
name: 'students',
initialState: {
list: [],
loading: false,
error: null,
},
reducers: {
// 同步 reducers...
},
// 3. 使用 extraReducers 处理异步 action
extraReducers: (builder) => {
builder
// pending:请求开始
.addCase(fetchStudents.pending, (state) => {
state.loading = true;
state.error = null;
})
// fulfilled:请求成功
.addCase(fetchStudents.fulfilled, (state, action) => {
state.loading = false;
state.list = action.payload;
})
// rejected:请求失败
.addCase(fetchStudents.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message;
});
},
});
export default studentsSlice.reducer;
二、在组件中使用
import
import { fetchStudents } from '../store/modules/students';
function StudentsList() {
const dispatch = useDispatch();
const { list, loading, error } = useSelector((state) => state.students);
useEffect(() => {
dispatch(fetchStudents());
}, [dispatch]);
if (loading) return <div>加载中...</div>;
if (error) return <div>错误: {error}</div>;
return (
<div>
{list.map((student) => (
<div key={student.id}>{student.name}</div>
))}
</div>
);
}