简体   繁体   中英

Date() constructor is rendering my page completely blank

When I'm using the built-in Date() constructor it's rendering my page completely blank

Current Output

Expected 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).

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.

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

** Because Date is an object and you cant render object as child**

// toDateString() will convert it into sting.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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