我有几个extraReducers,做同样的动作。我想知道我是否做对了:
const favouriteSlice = createSlice({
name: "favourite",
initialState: {
loading: true,
entities: "initial",
error: null,
},
reducers: {},
extraReducers:{
[addFavourite.pending && deleteFavourite.pending && getMyFavourites.pending]: (state) => {
state.loading = true
},
[addFavourite.fulfilled && deleteFavourite.fulfilled && getMyFavourites.fulfilled]: (state, action) => {
state.loading = false
state.entities = action.payload
},
[addFavourite.rejected && deleteFavourite.rejected && getMyFavourites.rejected]: (state, action) => {
state.loading = false
state.error = action.payload
},
}
})
我试着分别写每个extraReducer,它也工作,但它占用了很多空间。
这种方法是可以接受的,但是很难一眼就解析出每个extraReducer在做什么。
我会尝试用一些格式来提高可读性,像这样:
extraReducers: {
[addFavourite.pending &&
deleteFavourite.pending &&
getMyFavourites.pending]: (state) => {
state.loading = true;
},
[addFavourite.fulfilled &&
deleteFavourite.fulfilled &&
getMyFavourites.fulfilled]: (state, action) => {
state.loading = false;
state.entities = action.payload;
},
[addFavourite.rejected &&
deleteFavourite.rejected &&
getMyFavourites.rejected]: (state, action) => {
state.loading = false;
state.error = action.payload;
},
},