如何将createAsyncThunk与Typescript一起使用?如何设置"挂起"和"



现在我已经有了这些操作,用于上传thunk的生命周期。

type UPLOAD_START   = PayloadAction<void>
type UPLOAD_SUCCESS = PayloadAction<{ src: string, sizeKb: number }> 
type UPLOAD_FAILURE = PayloadAction<{ error: string }>

我想将其转换为createAsyncThunk调用,假设它会减少代码。但会吗?

从 https://redux-toolkit.js.org/api/createAsyncThunk 的例子来看,它应该是这样的:

const uploadThumbnail = createAsyncThunk(
'mySlice/uploadThumbnail',
async (file: File, thunkAPI) => {
const response = await uploadAPI.upload(file) as API_RESPONSE
return response.data   // IS THIS THE payload FOR THE fulfilled ACTION ?
}
)

这就是我如何处理生命周期操作?

const usersSlice = createSlice({
name: 'mySlice',
initialState: // SOME INITIAL STATE,
reducers: {
// standard reducer logic, with auto-generated action types per reducer
},
extraReducers: {
// Add reducers for additional action types here, and handle loading state as needed
[uploadThumbnail.pending]: (state,action) => {
// HANDLE MY UPLOAD_START ACTION
},
[uploadThumbnail.fulfilled]: (state, action) => {
// HANDLE MY UPLOAD_SUCCESS ACTION
},
[uploadThumbnail.rejected]: (state, action) => {
// HANDLE MY UPLOAD_FAILURE ACTION
},
}
})

问题

我假设createAsyncThunk异步处理程序的返回是fulfilled操作的payload,对吗?

但是,如何设置pendingrejected操作的payload类型?我是否应该向createAsyncThunk处理程序添加try-catch块?

这是我应该做的相关性吗?

  • pending === "UPLOAD_START"
  • fulfilled === "UPLOAD_SUCCESS"
  • rejected === "UPLOAD_FAILURE"

Obs:从我想象的模式来看,我编写的代码似乎不会比我已经用三个单独的动作并在我的常规化简器中处理它们的代码少(而不是在extraReducers道具上做)。在这种情况下使用createAsyncThunk有什么意义?

您的大多数问题都可以通过查看您链接的文档页面中更下方的 TypeScript 示例之一来回答:

export const updateUser = createAsyncThunk<
User,
{ id: string } & Partial<User>,
{
rejectValue: ValidationErrors
}
>('users/update', async (userData, { rejectWithValue }) => {
try {
const { id, ...fields } = userData
const response = await userAPI.updateById<UpdateUserResponse>(id, fields)
return response.data.user
} catch (err) {
let error: AxiosError<ValidationErrors> = err // cast the error for access
if (!error.response) {
throw err
}
// We got validation errors, let's return those so we can reference in our component and set form errors
return rejectWithValue(error.response.data)
}
})

const usersSlice = createSlice({
name: 'users',
initialState,
reducers: {},
extraReducers: (builder) => {
// The `builder` callback form is used here because it provides correctly typed reducers from the action creators
builder.addCase(updateUser.fulfilled, (state, { payload }) => {
state.entities[payload.id] = payload
})
builder.addCase(updateUser.rejected, (state, action) => {
if (action.payload) {
// Being that we passed in ValidationErrors to rejectType in `createAsyncThunk`, the payload will be available here.
state.error = action.payload.errorMessage
} else {
state.error = action.error.message
}
})
},
})

因此,从那里观察:

  • 使用 TypeScript 时,您应该对 extraReducers 使用builder样式表示法,您的所有类型都会自动为您推断。您永远不需要手动输入任何内容extraReducers
  • 你的 thunk 的returned 值将是"实现"操作的payload
  • 如果您return rejectWithResult(value),那将成为"拒绝"操作的payload
  • 如果你只是throw,那将成为"拒绝"操作的error

其他答案:

">
  • 待定"是您的"UPLOAD_START"。它没有有效负载,您无法设置它。 不过,所有三个"挂起"/"拒绝"/"已实现"都将具有action.meta.arg,这是您传递给 thunk 调用的原始值。
  • 最后,这可能比您手动编写的代码少一点,并且在整个应用程序中将非常一致。此外,它还捕获了一些否则看不到的错误。 你知道吗
const manualThunk = async (arg) => {
dispatch(pendingAction())
try {
const result = await foo(arg)
dispatch(successAction(result))
} catch (e) {
dispatch(errorAction(e))
}
}

实际上包含一个错误? 如果successAction触发了重新渲染(它很可能会触发),并且在重新渲染期间的某个地方,错误thrown,该错误将在此try..catch块中捕获,并将调度另一个errorAction。因此,您将同时遇到成功和错误情况。尴尬。这可以通过将结果存储在作用域变量中并在 try-catch-block 之外调度来规避,但实际上谁这样做?;) 正是这些createAsyncThunk为你照顾的小事,在我眼里是值得的。

这是我的方法,使用 SerializedError 类型

在src/store/reducer/api.ts中

... code
export const getFunction = createAsyncThunk("slice/type", async () => {
try {
const res = await axios.get("/url");
if (res.data) {
const data = res.data as unknown as {
someJSON: Type[];
};
return data;
}
} catch (e) {
const {
response: { data, status },
} = e as unknown as {
response: { data: string; status: number };
};
throw {
name: "Request Failed",
message: data,
code: `${status}`,
};
}
}); 
...code

在切片中,为拒绝案例添加相应的操作

/store/reducer/reducer.ts

export const Slice = createSlice({
name: "slice",
initialState: {message:"", type:""},
reducers: {},
extraReducers: (builder) => {
builder.addCase(getFunction.rejected, (state, action) => {
const { code } = action.error;
state.type = parseInt(code ?? "", 10) === 500 ? "error" : "warning";
state.message = "Failed to get response from server";
});
},
});

相关内容

  • 没有找到相关文章

最新更新