首页 > 解决方案 > 反应时间前没有得到日期

问题描述

我正在使用 react-timeago 包,我只需要通过道具从父组件获取数据,当我将数据放入 TimeAgo 的日期道具时,我什么也得不到。

props.date没有获取TimeAgo组件中的数据,我尝试过this.props.date但徒劳无功。下面的代码在同一个组件中

// this returns for ex 'Published 2 days ago'
<div>Published {props.date}</div>
// this returns only 'Published'
<div>Published <TimeAgo date={props.date} formatter={formatter}/></div>

标签: javascriptreactjs

解决方案


props.date返回的文字字符串不能直接转换为日期对象或日期字符串,首先您需要将其转换为标准格式,然后将其传递给props. 在return块之前添加此代码。

var calDate = stringToDate()

function stringToDate(){
 let cDate = new Date();
cDate.setDate(cDate.getDate() - parseInt(props.date)); //Get the integer part of X days ago, e.g return the integer 2 from 2 days ago and then subtract 2 days from current date.
//console.log(calDate.toString());
return cDate
}

将传递给 prop 的值更新为我们上面计算的值。

// this returns for ex 'Published 2 days ago'
<div>Published {props.date}</div>
// this returns only 'Published'
<div>Published <TimeAgo date={calDate} formatter={formatter}/></div>

推荐阅读