在我的案例中,有关错误的信息深深地位于响应中,我正在尝试将项目移至redux-toolkit
。以前是这样的:
catch(e) {
let warning
switch (e.response.data.error.message) {
...
}
}
问题在于redux-toolkit
并没有将数据放入rejected
动作创建者中,而且我无法访问错误消息,而是将他的消息而不是最初的消息放入了
原始回复如下:
那我该如何检索这些数据?
答案 0 :(得分:3)
根据文档,RTK的createAsyncThunk
具有错误的默认处理方式-它以Error
的形式分发action.error
实例的序列化版本。
如果您需要自定义rejected
操作中涉及的内容,则需要您自己来捕获初始错误,并且use rejectWithValue()
to decide what goes into the action:
const updateUser = createAsyncThunk(
'users/update',
async (userData, { rejectWithValue }) => {
const { id, ...fields } = userData
try {
const response = await userAPI.updateById(id, fields)
return response.data.user
} catch (err) {
if (!err.response) {
throw err
}
return rejectWithValue(err.response.data)
}
}
)
答案 1 :(得分:0)
对于那些使用 apisauce(使用带有标准化错误的 axios 的包装器 + 请求/响应转换)
由于 apisauce 总是解析 Promise,您可以检查 !response.ok
并使用 rejectWithValue
处理它。 (注意 ! 因为我们想检查请求是否不 ok)
export const login = createAsyncThunk(
"auth/login",
async (credentials, { rejectWithValue }) => {
const response = await authAPI.signin(credentials);
if (!response.ok) {
return rejectWithValue(response.data.message);
}
return response.data;
}
);
答案 2 :(得分:0)
我们使用 thunkAPI,payloadCreator 中的第二个参数; 包含通常传递给 Redux thunk 函数的所有参数以及其他选项:对于我们的示例,async(obj, {dispatch, getState, rejectWithValue, fulfillWithValue})
是我们的 payloadCreator,带有必需的参数;
这是一个使用 fetch api
的例子import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
export const getExampleThunk = createAsyncThunk(
'auth/getExampleThunk',
async(obj, {dispatch, getState, rejectWithValue, fulfillWithValue}) => {
try{
const response = await fetch('https://reqrefs.in/api/users/yu');
if (!response.ok) {
return rejectWithValue(response.status)
}
const data = await response.json();
return fulfillWithValue(data)
}catch(error){
throw rejectWithValue(error.message)
}
}
)
切片中的简单示例:
const exampleSlice = createSlice({
name: 'example',
initialState: {
httpErr: false,
},
reducers: {
//set your reducers
},
extraReducers: {
[getExampleThunk.pending]: (state, action) => {
//some action here
},
[getExampleThunk.fulfilled]: (state, action) => {
state.httpErr = action.payload;
},
[getExampleThunk.rejected]: (state, action) => {
state.httpErr = action.payload;
}
}
})
请注意:
rejectWithValue
- 实用程序(来自 thunkAPI 的附加选项),您可以在操作创建者中返回/抛出该实用程序,以返回具有已定义负载和元数据的拒绝响应。它会传递您给它的任何值,并在被拒绝操作的有效负载中返回它。