在redux工具箱中使用createEntityAdapter时如何处理错误



我有个问题。所以,我是新来的反应,现在我正在一个项目中工作。我使用redux工具箱来处理我的状态,我还使用createEntityAdapter来设置初始状态,问题是:当发生错误时,如何在使用createEntityAdapter时处理错误。还是我必须创建全局错误状态来处理asyncThunk的错误?使用全局错误状态好吗?

这是我的代码:

import { createSlice, createAsyncThunk ,createEntityAdapter } from '@reduxjs/toolkit'
export const searchRecipe = createAsyncThunk('recipes/SearchRecipe', async (title, { rejectWithValue }) => {
try {
const response = await axios.get(`/recipes?title=${title}`)
return response?.data?.data
} catch(err) {
return rejectWithValue(err?.response?.data?.message || 'Something went wrong')
}
})
const recipeAdapter = createEntityAdapter({
selectId: (recipe) => recipe.recipe_id
})
const recipeSlice = createSlice({
name: 'recipes',
initialState: recipeAdapter.getInitialState(),
extraReducers: {
[getRecipes.fulfilled]: (state, action) => {
recipeAdapter.setAll(state, action.payload)
}
}
})
export const recipeSelectors = recipeAdapter.getSelectors((state) => state.recipes)
export default recipeSlice.reducer

最后但并非最不重要。使用redux工具包(我可以阅读或观看资源(有更好的解决方案吗感谢

类似这样的东西:

import { createSlice, PayloadAction, createEntityAdapter } from "@reduxjs/toolkit";
import { PointType } from "../Types/PointType";
import { ErrorType } from "../Types/ErrorType";
type InitialStateType = {
data: PointType;
error: ErrorType;
};
export const pointsAdapter = createEntityAdapter<InitialStateType>({
selectId: point => point.data.Id,
sortComparer: (a, b) => a.data.Subject.localeCompare(b.data.Subject),
});
const initialState = pointsAdapter.getInitialState({
data: [],
error: { message: "" },
});
const pointSlice = createSlice({
name: "pointsSlice",
initialState,
reducers: {
fetchPointsSuccess: (state, action) => {
pointsAdapter.setAll(state, action.payload);
},
fetchSinglePointSuccsess: (state, action) => {
pointsAdapter.updateOne(state, action.payload);
},
fetchPointsFailure: state => {
state.error.message = "Can not fetch points";
},
updatePointsFailure: state => {
state.error.message = "Can not update point";
},
},
});
export const { fetchPointsSuccess, fetchPointsFailure, updatePointsFailure, fetchSinglePointSuccsess } =
pointSlice.actions;
export const pointReducer = pointSlice.reducer;

相关内容

  • 没有找到相关文章