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>
  );
}
相关推荐
小李科技10 小时前
【性能优化】事件委托:目标定位与 React/Vue 实战
前端·vue.js·react.js·面试·性能优化·前端框架
csj5010 小时前
前端基础之《React(16)—Modal组件封装》
前端·react.js
ZoeLandia2 天前
React11:数据请求与 TanStack Query
前端·react.js·typescript·react
瓦瓦gogo3 天前
实习中接触前端开发后,我开始了解 React
前端·react.js·前端框架
ZoeLandia3 天前
React08:自定义 Hook
开发语言·前端·react.js·typescript
空中湖5 天前
用 React 写数据大屏:为什么我不建议用图表库
前端·react.js·前端框架
来一首_We_go6 天前
React Flow Pro 高级交互实现
前端·react.js
weedsfly6 天前
React 不可变数据:为什么页面“明明数据变了却不更新
前端·javascript·react.js
随风一样自由6 天前
【React+TS71007】Next.js “use client” 误用导致 TS71007:客户端/服务端引入问题的完整排查与修复
前端·javascript·react.js
ZoeLandia7 天前
React6:组件通信
前端·react.js·typescript