我对redux工具包还不熟悉,但经过长时间的研究,我设法为redux工具包编写了这个配置,以便从我的后端Express API获取数据.如果我走对了,有谁能给我指路吗?
我应该使用createAsyncThunk还是这个配置也是正确的?
100
import { configureStore } from "@reduxjs/toolkit";
import productReducer from "./features/productSlice";
export const store = configureStore({
reducer: {
products: productReducer,
},
});
100
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
products: [],
isLoading: false,
error: null,
};
export const productsSlice = createSlice({
name: "products",
initialState,
reducers: {
startLoading: (state) => {
state.isLoading = true;
},
hasError: (state, action) => {
state.error = action.payload;
state.isLoading = false;
},
allProductsSuccess: (state, action) => {
state.products = action.payload;
state.isLoading = false;
},
},
});
export default productsSlice.reducer;
100
import axios from "axios";
import { productsSlice } from "./productSlice";
const { allProductsSuccess, startLoading, hasError } = productsSlice.actions;
export const fetchProducts = () => async (dispatch) => {
dispatch(startLoading());
try {
const { data } = await axios.get("/api/v1/products");
dispatch(allProductsSuccess(data.products));
} catch (e) {
dispatch(hasError(e?.response?.data?.message));
}
};
100
const { products, isLoading } = useSelector((state) => state.products);
console.log(products, isLoading)
useEffect(() => {
dispatch(fetchProducts());
}, []);
谢谢!