简体   繁体   English

反应时间前没有得到日期

[英]React time ago not getting date

I'm using react-timeago package, i just need to get the data from a parent component by props, when i put the data in the date prop of TimeAgo i get nothing.我正在使用 react-timeago 包,我只需要通过道具从父组件获取数据,当我将数据放入 TimeAgo 的日期道具时,我什么也得不到。

props.date is not getting the data in the TimeAgo component, i have tried this.props.date but in vain. props.date没有获取TimeAgo组件中的数据,我尝试过this.props.date但没有成功 the code below is in the same component下面的代码在同一个组件中

// 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>

Your props.date return a literal string that cannot be directly converted into a date object or date string, firstly you'll need to convert it into a standard format and then pass it to the props .您的props.date返回一个无法直接转换为日期对象或日期字符串的文字字符串,首先您需要将其转换为标准格式,然后将其传递给props Before the return block add this code.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
}

Update the value passed to prop to the value we calculated above.将传递给 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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