简体   繁体   English

Date() 构造函数使我的页面完全空白

[英]Date() constructor is rendering my page completely blank

When I'm using the built-in Date() constructor it's rendering my page completely blank当我使用内置的 Date() 构造函数时,它会使我的页面完全空白

Current Output当前Output

Expected Output预计 Output

import './ExpenseItem.css';

function ExpenseItem() {
 const expenseDate = new Date(2022, 1, 1)

  return (
      <div className='expense-item'>
          <div>{expenseDate}</div>
          <div className='expense-item__description'>
              <h2>Car Insurance</h2>
              <div className='expense-item__price'>$269.64</div>
          </div>
      </div>
  );
}

export default ExpenseItem; 

This is because you are trying to render a Date as a React child and Objects are not valid as a React child (the reason behind your blank screen).这是因为您试图将Date呈现为 React 子级,而Objects are not valid as a React child (空白屏幕背后的原因)。

Change your code to be like:将您的代码更改为:

const expenseDate = new Date(2022, 1, 1).toLocaleString();

In this way you will have a string instead, that is a valid React child.通过这种方式,您将获得一个字符串,它是一个有效的 React 子代。

Check the documentation on how to change your date-to-string format:查看有关如何更改日期到字符串格式的文档:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

** Because Date is an object and you cant render object as child** ** 因为 Date 是 object 并且您不能将 object 渲染为孩子**

// toDateString() will convert it into sting. // toDateString()会将其转换为字符串。

const expenseDate = new Date(2022, 1, 1).toDateString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM