React应用中渲染Date对象报错,如何正确显示当前日期?
我正在学习React,尝试显示当前日期时出现报错。创建了一个Date对象存储在变量中,随后在h2标签中进行渲染,代码如下:
import logo from './logo.svg'; import './App.css'; function App() { const curr_tim= new Date(); console.log(curr_tim); return ( <div className='container'> <h1> React Clock </h1> <h2>Current Date is:{curr_tim}</h2> </div> ); } export default App;
报错信息如下:
Uncaught Error: React子节点不能是对象(发现:[object Date])。如果你想渲染子元素集合,请改用数组。
at throwOnInvalidObjectType (react-dom.development.js:14887:1)
at updateSlot (react-dom.development.js:15202:1)
at reconcileChildrenArray (react-dom.development.js:15349:1)
at reconcileChildFibers (react-dom.development.js:15821:1)
at reconcileChildren (react-dom.development.js:19174:1)
at updateHostComponent (react-dom.development.js:19924:1)
at beginWork (react-dom.development.js:21618:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
问题原因
React不允许直接将对象作为子节点渲染,curr_tim是一个Date对象,不属于React可直接渲染的类型(如字符串、数字、React元素等)。
解决方法
将Date对象转换为字符串即可,有几种常用方式:
- 使用
toString()方法:直接转换为默认格式的字符串
<h2>Current Date is:{curr_tim.toString()}</h2>
- 使用本地化格式方法:根据地区自定义显示格式,更友好
// 显示完整的本地化日期时间 <h2>Current Date is:{curr_tim.toLocaleString()}</h2> // 仅显示日期部分 <h2>Current Date is:{curr_tim.toLocaleDateString()}</h2> // 仅显示时间部分 <h2>Current Date is:{curr_tim.toLocaleTimeString()}</h2>
修改后的完整代码
import logo from './logo.svg'; import './App.css'; function App() { const curr_tim= new Date(); console.log(curr_tim); return ( <div className='container'> <h1> React Clock </h1> <h2>Current Date is:{curr_tim.toLocaleString()}</h2> </div> ); } export default App;
内容的提问来源于stack exchange,提问作者SHOBHIT GUPTA

