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

React+Redux开发社交应用时无法为Firebase拉取的帖子分配id如何解决

问题排查与修复方案

问题1:拉取数据时id为undefined

错误原因

Firebase实时数据库调用GET接口拉取集合数据时,返回的response.data是「以节点ID为key、以节点内容为value」的对象集合,你循环遍历的key才是每个帖子对应的Firebase name属性(即节点ID),原代码错误读取了整个集合的name属性(该属性不存在,所以返回undefined)。

修正代码

修改FetchPost action里的循环逻辑:

export const FetchPost = () => {
    return dispatch => {
        dispatch(FetchPostStart());
        axios.get('/Data.json')
        .then(response => {
            const fetchedData = [];
           for(let key in response.data){
                   fetchedData.push({
                   ...response.data[key],
                   // 把原代码的response.data.name改成key
                   id: key
               });
           }
           dispatch(FetchPostSuccess(fetchedData));
        })
        .catch(error => {
            dispatch(FetchPostError(error));
        });
    }
}

问题2:删除时传递的id为null

错误原因

新增帖子成功后的reducer逻辑错误,你没有把id放到帖子对象里,而是把id作为单独元素加到了Data数组末尾,导致新增的帖子对象本身没有id属性,调用删除时自然拿不到正确的id值。同时删除成功的reducer没有过滤已删除的帖子,会导致前端数据和后端不同步。

修正代码

修改New_Post_Success对应的reducer逻辑:

case actionTypes.New_Post_Success: 
        const {Comment, ImageUrl, Date, User} = action.payload.data;
        const id = action.payload.index;
        console.log(id+"Reducer function")
        return {
         ...state,
         loading: false,
         // 把id放到帖子对象内部,不要单独加为数组元素
         Data: [
           ...state.Data, 
           {Comment, ImageUrl, Date, User, id}
          ],
        }

如果需要删除后前端同步更新,补充Delete_Post_Success的reducer逻辑:

case actionTypes.Delete_Post_Success:  
        return {
            ...state,
            loading: false,
            // 过滤掉已删除的帖子
            Data: state.Data.filter(item => item.id !== action.ID)
          }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:15:00