声明函数,
它接受一个字符串标识符和一个payload创建者回调,执行实际的异步逻辑,并返回一个Promise,该Promise将根据你返回的Promise处理相关动作的调度,以及你的reducers中可以处理的action类型。
import axios from "axios";
import { createAsyncThunk } from "@reduxjs/toolkit";
export const GetPosts = createAsyncThunk(
"post/getPosts", async () => await axios.get(`${BASE_URL}/posts`)
);
export const CreatePost = createAsyncThunk(
"post/createPost",async (post) => await axios.post(`${BASE_URL}/post`, post)
);
在切片中处理
import { createSlice } from "@reduxjs/toolkit";
import { GetPosts, CreatePost } from "../../services";
export const initialState = {
posts: [],
loading: false,
error: null,
};
export const postSlice = createSlice({
name: "post",
initialState: initialState,
extraReducers: {
[GetPosts.fulfilled]: (state, action) => {
state.posts = action.payload.data;
},
[GetPosts.rejected]: (state, action) => {
state.posts = [];
},
[CreatePost.fulfilled]: (state, action) => {
state.posts.unshift(action.payload.data);
},
},
});
export default postSlice.reducer;