Redux-Toolkit createAsyncThunk函数不返回错误

yzxexxkh  于 2022-11-12  发布在  其他
关注(0)|答案(2)|浏览(193)

我正在使用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;
2o7dmzc5

2o7dmzc51#

当您对一个值执行return操作时,您是在告诉createAsyncThunk这是一个成功的fulfilled请求,并且返回的值变为action.payload
如果您完全跳过错误捕获,而只是让axios.get()调用抛出并拒绝promise本身,它将正确地调度rejected操作。
如果您希望thunk的结果被视为rejected,但您希望自定义操作的内容,则需要使用rejectWithValue()实用工具,如我们文档中所示:
https://redux-toolkit.js.org/api/createAsyncThunk#handling-thunk-errors

x33g5p2x

x33g5p2x2#

要打印错误,请执行以下操作:

[getPosts.rejected]: (state, action) => {
  console.log(action.error)
},

相关问题