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

Reactjs时间戳转日期映射及MUIDataTable渲染报错问题

报错根因

你遇到的报错是因为代码中直接把Date类型对象start_date传入了MUIDataTable的数据源,React无法直接将JS对象作为子元素渲染,才触发了该错误提示:

Objects are not valid as a React child. if you meant to render a collection of children, use an array instead

解决方法

只需要把Date对象转换为可渲染的字符串格式即可,常用转换方式有以下几种:

  • 转本地友好格式:调用toLocaleString()方法,输出符合当地阅读习惯的日期时间字符串,例如2021/11/30 03:00:00
  • 转ISO标准格式:调用toISOString()方法,输出国际标准格式的日期时间字符串,例如2021-11-29T19:00:00.000Z
  • 自定义格式:如果有特定格式需求,可以手动拼接年月日时分,或者引入dayjs等轻量日期库做格式化
修正后代码示例
const timestamp = Object.keys(data).map((id, index) => {
      var startDate = data[id].start_date.seconds
      var start_date = new Date(startDate*1000);
      console.log(start_date)
      // Tue Nov 30 2021 03:00:00 GMT+0800 (Standard Time)
      return [
        index + 1,
        data[id].eventTitle,
        data[id].venue,
        start_date.toLocaleString(), // 将Date对象转为字符串后再传入
        data[id].end_date.seconds,
]})

<MUIDataTable data={timestamp}/>
补充说明

如果需要保留Date对象用于表格的日期排序、筛选逻辑,也可以不在map阶段转换,而是在MUIDataTable的columns配置项中,给对应日期列配置customBodyRender方法,在渲染时再做格式转换,同样可以避免报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:15:06