Рич*_*ман 8 redux react-redux redux-toolkit
我的案例中有关错误的信息深深地存在于响应中,我正试图将我的项目移至redux-toolkit
. 这是以前的样子:
catch(e) {
let warning
switch (e.response.data.error.message) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
问题是redux-toolkit
没有将这些数据放在rejected
动作创建者中,而且我无法访问错误消息,它将他的消息而不是最初的消息:
虽然原始响应如下所示:
那么我怎样才能检索到这些数据呢?
mar*_*son 12
根据文档,RTKcreateAsyncThunk
具有默认的错误处理方式——它将Error
实例的序列化版本作为action.error
.
如果您需要自定义rejected
操作中的内容,则由您自己捕获初始错误,并用于rejectWithValue()
决定操作中的内容:
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)
}
}
)
Run Code Online (Sandbox Code Playgroud)
小智 7
我们使用thunkAPI,payloadCreator 中的第二个参数;包含通常传递给 Redux thunk 函数的所有参数,以及其他选项:对于我们的示例,async(obj, {dispatch, getState, rejectWithValue, fulfillWithValue})
我们的 PayloadCreator 具有所需的参数;
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)
}
}
)
Run Code Online (Sandbox Code Playgroud)
切片中的简单示例:
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;
}
}
})
Run Code Online (Sandbox Code Playgroud)
请注意:
rejectWithValue
- 实用程序(来自 thunkAPI 的附加选项),您可以在操作创建者中返回/抛出该实用程序,以返回带有定义的有效负载和元的拒绝响应。它将传递您赋予它的任何值,并将其返回到被拒绝操作的有效负载中。
归档时间: |
|
查看次数: |
6386 次 |
最近记录: |