我正在做一个简单的电子商务应用程序,我想展示所有的产品。我使用redux工具包,根据文档,我找不到任何地方如何处理错误。这是我的产品切片:
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from 'axios';
export const getProducts = createAsyncThunk(
'/products/getProducts',
async () => {
const { data } = await axios.get('/api/v1/products');
return data;
}
);
const initialState = {
loading: false,
products: [],
product: {},
error: '',
};
export const productsSlice = createSlice({
name: 'products',
initialState,
reducers: {},
extraReducers: {
[getProducts.pending]: state => {
state.loading = true;
},
[getProducts.fulfilled]: (state, { payload }) => {
state.loading = false;
state.products = payload;
},
[getProducts.rejected]: (state, { payload }) => {
state.loading = false;
state.error = payload;
},
},
});
export const productsReducer = productsSlice.reducer;
1条答案
按热度按时间ego6inou1#