我正在开发一个有多个切片的应用程序。我将createAsyncThunk
用于API调用,我喜欢它,因为它为API请求的不同状态提供了操作创建者,这样我就可以跟踪reducer中的加载状态和错误。但我的问题是,如果我想有一个单独的reducer来跟踪API调用的loading
、error
和success
,该怎么办?如何使用redux-toolkit
实现这一点
我知道我可以在createAsyncThunk
函数中执行dispatch
操作,但感觉不对,有点违背了函数本身的目的。此外,减速器内部的副作用被认为是一种不良做法。所以,在这一点上,我有点困惑,我想在应用程序的根目录中只有一个Loader
组件,当加载状态为真时,它会被触发,而加载的确切内容并不重要
下面是我当前代码的一个示例:
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { AxiosError } from 'axios'
import { masterInstance } from 'api'
import { GetAccessCodeParams, RegistrationStateType } from 'store/slices/registration/types'
export const getAccessCodeRequest = createAsyncThunk<void, GetAccessCodeParams, { rejectValue: { message: string } }>(
'registration/getAccessCodeRequest',
async ({ email }, { rejectWithValue }) => {
try {
await masterInstance.post(`/authorization/getAccessCodeWc`, { email })
} catch (err) {
let error: AxiosError = err
if (error) {
return rejectWithValue({
message: `Error. Error code ${error.response?.status}`,
})
}
throw err
}
}
)
const initialState: RegistrationStateType = {
isLoading: false,
error: null,
}
const registrationSlice = createSlice({
name: 'registration',
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(getAccessCodeRequest.fulfilled, (state) => {
state.isLoading = false
state.error = null
})
builder.addCase(getAccessCodeRequest.pending, (state) => {
state.isLoading = true
state.error = null
})
builder.addCase(getAccessCodeRequest.rejected, (state, action) => {
if (action.payload) {
state.error = {
message: action.payload.message,
}
} else {
state.error = action.error
}
state.isLoading = false
})
},
})
export const registrationReducer = registrationSlice.reducer
我希望isLoading
和error
在一个单独的减速器中
您可以有一个共享的reducer-matcher函数。
// mySharedStuff.js
export const handleLoading = (action, (state) => {
state.loading = action.type.endsWith('/pending'); // or smth similar
});
export const handleError = (action, (state) => {
state.error = action.type.endsWith('/rejected'); // or smth similar
});
// mySlice.js
const mySlice = createSlice({
name: 'FOO',
initialState: {},
reducers: {},
extraReducers: builder => {
builder.addMatcher(handleLoading),
builder.addMatcher(handleError),
...