You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux数据未存入Store问题排查:新增调用后数据不显示

问题:Redux异步请求数据无法存入Store

我在前端代码中新增Redux调用后,数据无法存入store。fetch请求能正常执行,但dispatch的payload为空,组件通过useSelector无法获取到数据,同项目内类似逻辑的代码可正常运行。相关代码如下:

Store定义

const store = configureStore({
    reducer: {
        login: loginSlice.reducer,
        cart: cartSlice.reducer,
        product: productSlice.reducer,
        notification: notificationSlice.reducer
    }
});

Product切片

const productSlice = createSlice({
    name: 'product',
    initialState: {
        products: []
    },
    reducers: {
        replaceData(state,action) {
            console.log(action)
            state.products = action.payload.products;
        }
    }
  
});

export const productActions = productSlice.actions

export default productSlice

异步Action

export const fetchProducts = () => {
    return async (dispatch) => {
        const fetchHandler = async () => {
            const resp = await fetch("https://shoppingcart-a62bb-default-rtdb.europe-west1.firebasedatabase.app/products.json")
            const data = await resp.json();
            
        }

        try {
            const productData = await fetchHandler();
            dispatch(productActions.replaceData(productData))
        } catch (err) {
            dispatch(notificationActions.showNotification({
                open: true,
                message: "Error reading product data",
                type: 'error'
            }));
        }
    }
}

APP.js中的调用

useEffect(()=>{
  dispatch(fetchCartData())
  dispatch(fetchProducts())
},[dispatch]);

组件中读取Store数据

let respProducts = useSelector(state => state.product.products);
console.log(respProducts)

问题原因与修复方案

核心问题

异步Action中的fetchHandler函数没有返回获取到的数据,导致productData为undefined,dispatch时传递的payload是空值,最终reducer无法拿到有效数据。

修复步骤

  1. 给fetchHandler添加返回值,并且匹配reducer期望的结构(reducer中取action.payload.products):
const fetchHandler = async () => {
    const resp = await fetch("https://shoppingcart-a62bb-default-rtdb.europe-west1.firebasedatabase.app/products.json")
    const data = await resp.json();
    // Firebase返回的通常是对象格式(如{id1: {...}, id2: {...}}),需转成数组再包装结构
    return { products: Object.values(data) };
}
  1. 如果Firebase返回的本身就是数组,直接返回{ products: data }即可。

修改后,productData会拿到正确的数据结构,dispatch后reducer就能将数据存入store,组件通过useSelector即可获取到products数据。


内容的提问来源于stack exchange,提问作者fghf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 12:36:14