gpt4 book ai didi

javascript - 无法在ReactJS中显示JSX中的日期

转载 作者:行者123 更新时间:2023-11-28 13:07:49 24 4
gpt4 key购买 nike

下面是我的代码,如果我用字符串初始化测试,它可以正常工作,但如果我将其更改为 new Date() 它会抛出错误。让我知道我刚开始使用 React 时做错了什么。

代码-

import React from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';

class App extends React.Component {
render() {
//let test = 'this is a string'; // WORKING FINE
let test = new Date();
return (
<div>
<h1>Hello World</h1>
<p>{test}</p>
</div>
);
}
}

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

错误 -

Objects are not valid as a React child (found: Fri Jul 21 2017 02:11:18 GMT+0530 (India Standard Time)). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.

最佳答案

您看到这一点是因为 Date 是一个对象而不是字符串。要让它在没有库的情况下正常工作:

import React from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';

class App extends React.Component {
render() {
//let test = 'this is a string'; // WORKING FINE
let test = new Date();
return (
<div>
<h1>Hello World</h1>
<p>{test.toString()}</p>
</div>
);
}
}

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

对日期对象调用 toString() 方法。

关于javascript - 无法在ReactJS中显示JSX中的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45224856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com