简体   繁体   中英

React - rendering with moment.js

I am trying to render this:

<p>Some date: {moment('12-25-1995', 'MM-DD-YYYY')}</p>

and getting error

Uncaught Invariant Violation: Objects are not valid as a React child (found: Mon Dec 25 1995 00:00:00 GMT+0100). 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. Check the render method of `MeetingComponent`.

I see this is a common React response when trying to output objects.

What would be the best practice solution for this?

You should use Moment's format function to return a string, otherwise you're trying to render a Moment Object!

<p>Some date: {moment('12-25-1995', 'MM-DD-YYYY').format('MM/DD/YYYY')}</p>

Let me explain this more thoroughly: the moment constructor can handle two parameters, the first being the date and the second being the format of the date passed as the first parameter. This has nothing to do with rendering the date, it just allows MomentJS to create a correct representation of your date, and the second parameter can be omitted when using the standard YYYY-MM-DD format.

Once you have a Moment Object, you can do some neat things with it, such as adding days, diffing two dates, format a date in any format, etc...

If you already have the date in your desired format, you don't need to use Moment to print it - you already have the correct string. But you can use moment change the format of your date and print it in some other:

<p>Some date: {moment('12-25-1995', 'MM-DD-YYYY').format('YYYY/MM/DD')}</p>

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