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

将MongoDB数据加载至Redux Store并渲染表格遇问题求助

问题解决:Redux数据渲染失败

核心问题分析

你的代码存在以下关键问题导致数据无法正常渲染:

  • 状态属性名不匹配:组件中尝试获取ordersTotal,但Redux状态中对应的属性是total
  • 数据访问路径错误:未正确获取月份数据(API返回的月份嵌套在_id.month中)
  • 初始状态设置不当:total初始值为[""],与API返回的对象数组结构不兼容
  • 表格列映射错误:月份列未填充数据,价格列重复显示

修正后的代码

1. 修正Total组件

import React, { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux';
import { fetchTotal } from './redux/orderApiCall';

export default function Total() {
  const dispatch = useDispatch();
  // 修正:获取正确的状态属性total
  const { total } = useSelector(state => state.order);

  useEffect(() => {
    dispatch(fetchTotal());
  }, [dispatch]); // 添加dispatch到依赖数组(符合React Hooks最佳实践)
  
  return (
    <table className="table">
    <thead>
      <tr>
        <th>Id</th>
        <th>Month</th>
        <th>Price</th>
      </tr>
    </thead>
    <tbody>
      {/* 修正:使用total数组,正确访问月份和价格字段 */}
      {total?.map((item, index) => (
        <tr key={item._id}>
          <td>{index + 1}</td>
          <td>{item._id.month}</td> {/* 渲染月份 */}
          <td>{item.price}</td> {/* 渲染总金额 */}
        </tr>
      ))}
    </tbody>
  </table>
  )
}

2. 修正orderSlice.js中的初始状态

import { createSlice } from "@reduxjs/toolkit";

const orderSlice = createSlice({
   name: "order",
   initialState: {
    orders: [],
    order: null,
    // 修正:初始值改为空数组,匹配API返回的对象数组结构
    total: [],
   },
   reducers: {
      addOrder(state, action) {
         state.orders.push(action.payload);
      },  
      setOrders(state, action) {
         state.orders = action.payload;
       },
       setOrder(state,action) {
         state.order = action.payload;
       },
       setTotal(state,action) {
         state.total = action.payload;
       },
   }
});

const orderReducer = orderSlice.reducer;
const orderActions = orderSlice.actions;

export { orderActions, orderReducer }

额外优化建议

  • 可以添加加载状态提示,避免数据未返回时表格为空的情况
  • 对月份进行格式化(例如将数字1转换为"一月")提升用户体验
  • 可在API调用中添加loading状态管理,在数据请求过程中显示加载动画

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 09:03:15