【问题标题】:React/date-fns - error in component 'Objects are not valid as a React child' when using 'addSuffix'React/date-fns - 使用“addSuffix”时组件“对象作为 React 子项无效”中的错误
【发布时间】:2020-10-07 01:26:59
【问题描述】:

我创建了一个使用date-fnsformatDistanceToNow 方法的组件。它工作正常,但是当我想使用 addSuffix 选项时,React 会抛出以下错误:

Unhandled Runtime Error Error: Objects are not valid as a React child (found: object with keys {addSuffix}). If you meant to render a collection of children, use an array instead.

import * as React from 'react'
import { format, parseISO, formatDistanceToNow } from 'date-fns';

function DateDistance({ text, dateString }) {
  const date = parseISO(dateString);
  return (
    <>
      <div className="text-xs font-medium text-gray-700">
        <span>{text}</span>
        <time>
          {(formatDistanceToNow(date), { addSuffix: true })}
        </time>
      </div>
    </>
  );
}

function BlogPost({ post }) {
  return (
   <>
    <h2>Hello World!</h2>
    <p>This will be the subheader and below will be the published and updated date values.</p>
    <DateDistance
      text="and was updated "
      dateString={post.updated_at}
    />
   </>
  )
}

【问题讨论】:

  • 在您调用{(formatDistanceToNow(date), { addSuffix: true })} 时有一个拼写错误,因为 addSuffix 是 formatDistanceToNow 的参数

标签: reactjs date date-fns


【解决方案1】:

formatDistanceToNow(日期,[选项])

<time>{formatDistanceToNow(date, { addSuffix: true })}</time>

【讨论】:

    猜你喜欢
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 2021-05-12
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    相关资源
    最近更新 更多