createAsyncThunk

一、 创建异步函数

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>
  );
}
相关推荐
YAwu112 小时前
深入解析 React 炫彩鼠标跟随标题组件:从坐标定位到动画性能
前端·react.js
Ruihong10 小时前
🎉 VuReact 1.9.0 发布,支持 Vue 3.4 defineModel 编译到 React
vue.js·react.js·面试
spmcor10 小时前
React 架构师之路:Next.js 全栈革命(第八篇)
前端·react.js
假如让我当三天老蒯10 小时前
React基础、进阶(学习用)
前端·react.js·面试
spmcor10 小时前
为什么页面越用越卡?——React组件内存泄漏的排查与修复
react.js
天蓝色的鱼鱼1 天前
React Router v8 来了:react-router-dom 没了,老项目该怎么迁移?
前端·react.js
无名氏同学1 天前
React 16-19 新特性
react.js
写代码的皮筏艇1 天前
React中的forwardRef
前端·react.js·面试
不知疲倦的老鸟1 天前
Node.js 库在浏览器里跑不了的教训
react.js·next.js