javascript - 反应时间前没有得到日期
问题描述
我正在使用 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>
解决方案
您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>
推荐阅读
- url - 使用 octave 从 url 中提取和读取 grib2 文件
- blazor - 当有异步方法调用时,为什么 Blazor 生命周期方法会乱序执行?
- node.js - 我在导入 @google-cloud/storage 时遇到错误
- reactjs - 使用反应钩子重新加载组件
- python - 这是我尝试标记推文时python返回的内容:TypeError:列表索引必须是整数或切片,而不是str
- javascript - 无法使用 ..\ 路径语法从 atom 中的父目录访问 p5.js 库
- swift - Swift - TableViewCell - 布局边距不起作用
- c - 具有开放散列 C 的静态列表
- reactjs - 保存在我的数据库中并每天检查一次 api (Strapi + react)
- cluster-computing - 使用 qsub 取消所有等待的作业