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

React渲染Date对象报Objects are not valid as a React child问题咨询

报错触发原因

React 仅支持直接渲染字符串、数字、React 元素、数组/片段等类型作为子元素,new Date() 生成的是 Date 实例对象,不属于可直接渲染的合法类型,因此触发报错。
你使用 new Date().getFullYear() 时返回值是数字类型,属于 React 可直接渲染的类型,所以运行正常。

解决方案

你需要的「Mon Aug 23 2021 19:00:04」格式刚好是 Date 对象默认的字符串序列化结果,直接调用 toString() 方法将 Date 对象转为字符串即可,修改后的代码如下:

import React from "react";
import ReactDOM from "react-dom";

const date = new Date();

ReactDOM.render(
  <div>
    <h1> {date.toString()} </h1>
  </div>,
  document.getElementById("root")
);

如果后续需要自定义日期格式,也可以手动拼接 getFullYear()、getMonth()、getDate() 等方法的返回值,或者使用 toLocaleString() 方法配合参数调整输出格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 23:18:05