【问题标题】:How to print JavaScript new Date() in React?如何在 React 中打印 JavaScript new Date()?
【发布时间】:2018-04-25 14:12:23
【问题描述】:

我无法在 React 中打印简单的 JavaScript 日期。

import React, { Component } from 'react';
import './ActivityWarningText.css';

class ActivityWarningText extends Component {

        render() {
            const str = new Date();
            return(
          <div>
            <h1>All activity is recorded. {str}</h1>
          </div>
         )
        }

}

export default ActivityWarningText;

我收到此错误:

Objects are not valid as a React child (found: Wed Apr 25 2018 18:09:03 GMT+0400 (Arabian Standard Time)). If you meant to render a collection of children, use an array instead.
    in h1 (at index.js:17)
    in div (at index.js:16)
    in ActivityWarningText (at index.js:34)
    in component (created by Route)
    in Route (at index.js:34)
    in div (at index.js:33)
    in div (at index.js:30)
    in Router (created by BrowserRouter)
    in BrowserRouter (at index.js:29)
    in App (at withAuthentication.js:36)
    in WithAuthentication (at index.js:14)

不过,这可行,str.getFullYear()

【问题讨论】:

  • 这个错误告诉你你需要知道的一切。如果str 是对象,则{str} 无效。它必须是一个字符串。 Date提供了很多转换为字符串的函数,如date.toISOString()date.toDateString();

标签: javascript reactjs datetime


【解决方案1】:

Date 对象必须转换为字符串。你可以试试

{str.toString()}

{`${str}`}

【讨论】:

  • 每个对象都可以这样做吗?甚至像 JSON 这样的带有子数组的对象?
  • 它可以应用于任何在其界面中有toString的东西,所以是的。
【解决方案2】:

new Date(); 给你一个对象。你不能在 React 中将对象渲染为子对象。您可以使用toString() 获得日期的字符串化版本。

【讨论】:

    【解决方案3】:

    对象不能作为子组件注入到反应组件中。 您可以使用 date.toISOString() 函数将日期对象转换为可以作为子元素呈现给反应组件的事物。

    【讨论】:

      猜你喜欢
      • 2022-06-17
      • 2020-08-23
      • 2015-08-16
      • 1970-01-01
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多