我正在使用Redux Toolkit的createAsyncThunk函数来处理api请求。当关闭网络时,以下函数返回action。payload=“Network Error”,status =“success”。状态应该是“error”。但是它返回了成功。有什么建议可以解决这个问题吗?提前感谢。
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";
import { GET_POSTS_API } from "./APIs";
const initialState = { posts: [], status: "idle", error: null };
export const getPosts = createAsyncThunk("posts/getPostsStatus", async () => {
try {
const { data } = await axios.get(GET_POSTS_API);
return data;
} catch (error) {
return error.response ? error.response.data.message : error.message;
}
});
export const postsSlice = createSlice({
name: "posts",
initialState,
reducers: {},
extraReducers: {
[getPosts.pending]: (state, action) => {
state.status = "loading";
},
[getPosts.fulfilled]: (state, action) => {
state.status = "success";
state.posts = action.payload;
},
[getPosts.rejected]: (state, action) => {
state.status = "error";
state.error = action.payload;
},
},
});
export default postsSlice.reducer;
2条答案
按热度按时间2o7dmzc51#
当您对一个值执行
return
操作时,您是在告诉createAsyncThunk
这是一个成功的fulfilled
请求,并且返回的值变为action.payload
。如果您完全跳过错误捕获,而只是让
axios.get()
调用抛出并拒绝promise本身,它将正确地调度rejected
操作。如果您希望thunk的结果被视为
rejected
,但您希望自定义操作的内容,则需要使用rejectWithValue()
实用工具,如我们文档中所示:https://redux-toolkit.js.org/api/createAsyncThunk#handling-thunk-errors
x33g5p2x2#
要打印错误,请执行以下操作: