Redux Toolkit获取产品数据后products数组为空,求技术排查
问题描述
使用Redux Toolkit获取产品对象数组时,API已返回数据,但state中的products数组始终为空。相关代码如下:
GET API
export const getProductsApi = async () => { const response = await fetch( `${gateway.url}/products`, { headers: { "Content-Type": "application/json", Accept: "application/json", }, } ); const data = await response.json(); return data; }
REDUX ACTION
import { getProductsPending, getProductsSuccess, getProductsFailed, } from "../../slices/get-products"; import { getProductsApi } from "../../../api/get-products"; export const getProducts = () => async (dispatch: any) => { dispatch(getProductsPending()); try { const response = await getProductsApi(); const data = response.data; console.log('products redux here', data); dispatch(getProductsSuccess(data)); } catch (error) { dispatch(getProductsFailed(error)); } };
REDUX SLICE
const getProductsSlice = createSlice({ name: "getProducts", initialState, reducers: { getProductsPending: (state) => { state.isLoading = true; state.error = ""; }, getProductsSuccess: (state, action: PayloadAction<Product[]>) => { state.isLoading = false; state.products = action.payload; state.error = ""; }, getProductsFailed: (state, action) => { state.isLoading = false; state.error = action.payload.error; state.products = []; }, }, }); const { reducer, actions } = getProductsSlice; export const { getProductsPending, getProductsSuccess, getProductsFailed } = actions; export default reducer;
REDUX STORE
import { configureStore } from "@reduxjs/toolkit"; import getProductsReducer from "../redux/slices/get-products"; const store = configureStore({ reducer: { products: getProductsReducer, }, }); store.subscribe(() => console.log(store.getState())); export default store;
排查与解决方案
修正API响应数据的取值逻辑
你的getProductsApi直接返回了response.json()的结果,如果后端API返回的是产品数组本身而非包含data字段的对象,那么response.data会是undefined,导致getProductsSuccess接收的 payload 为空。
修改action中的代码:// 把 const data = response.data; 改为 const data = response;如果后端确实返回
{ data: [...] }结构,先确认console.log('products redux here', data)的输出是否为有效数组,若输出undefined则需检查API返回格式。确认initialState的定义
检查slice中initialState的配置,确保包含products: []字段,否则无法正确赋值:const initialState = { isLoading: false, error: "", products: [] // 必须存在这个初始数组 };验证组件中的state获取逻辑
确保组件中使用useSelector时路径正确:// 从store的products reducer下获取products数组 const products = useSelector((state) => state.products.products);检查错误处理逻辑
若API请求出现隐藏错误,getProductsFailed会将products重置为空数组。可以在catch块中打印错误信息排查问题:catch (error) { console.error('获取产品失败:', error); dispatch(getProductsFailed(error)); }
内容的提问来源于stack exchange,提问作者Arthur Prasniski
相关产品推荐
相关产品推荐

