如何解决使用Redux-Toolkit处理错误
在我的案例中,有关错误的信息深深地位于响应中,我正在尝试将项目移至redux-toolkit
。以前是这样的:
catch(e) {
let warning
switch (e.response.data.error.message) {
...
}
}
问题在于redux-toolkit
并没有将数据放入rejected
动作创建者中,而且我无法访问错误消息,而是将他的消息而不是最初的消息放入了
原始回复如下:
那我该如何检索这些数据?
解决方法
根据文档,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)
}
}
)
,
对于那些使用 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;
}
);
,
我们使用 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,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 的附加选项),您可以在操作创建者中返回/抛出该实用程序,以返回具有已定义负载和元数据的拒绝响应。它会传递您给它的任何值,并在被拒绝操作的有效负载中返回它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。