reactjs Tracker重新计算函数出现异常,RangeError:时间值无效|React,流星,

aydmsdu9  于 2022-12-12  发布在  React
关注(0)|答案(1)|浏览(155)

我收到一个错误消息,显示Exception from Tracker recompute functionRangeError: Invalid time value
问题是有时候card会得到undefined,因为它是未定义的,所以我不能运行它:const dateFormat = isThisYear(createdAt) ? "MMM d" : "MMM d, yyyy";
有没有办法只在卡有值的时候才执行dateFormat

import React from "react";
import Child from "./Child";
import { format, isThisYear } from "date-fns";

const Sample = ({ card }) => {
  const { createdAt, title } = card || {};

  const dateFormat = isThisYear(createdAt) ? "MMM d" : "MMM d, yyyy";
  const createdDate = format(createdAt, dateFormat);

  return (
    <>
      <Child createdDate={createdDate} />
    </>
  );
};

export default Sample;
pepwfjgg

pepwfjgg1#

这不一定是一个Meteor.js问题,但更多的是一个普通的javascript问题,你应该在返回变量之前检查它们的真实性。在这种情况下,createdAt和(或)title。我可能会像下面这样处理你的情况。

import React from "react";
import Child from "./Child";
import { format, isThisYear } from "date-fns";
  
const Sample = ({ card }) => {
  const { createdAt, title } = card || {};
  if (createdAt) {
    const dateFormat = isThisYear(createdAt) ? "MMM d" : "MMM d, yyyy";
    const createdDate = format(createdAt, dateFormat);
  }
  if (createdDate) {
    return (
     <>
       <Child createdDate={createdDate} />
     </>
    );
  } else {
    return (
     <>
       <Child createdDate={} />
     </>
    );   
  }
};
  
export default Sample;

相关问题