我想检查我的数据何时更新。 -当我点击“更新”按钮时,它显示“立即更新” -如果距离我的热门歌曲只有n分钟,则会显示“ n分钟之前” -如果距离我的点击时间n小时,则显示“ n小时前”
我该如何做出反应?
this.state = {
dataUpdate: null
}
handleUpdate() {
const now = moment().format();
getTimeDiff(now);
}
getTimeDiff(now) {
cost timeDiff = moment(now).startOF('hour').fromNow();
return timeDiff;
}
render() {
return (
<Data />
<p>dataUpdate</p>
)
}
其他问题是timeDiff
继续填充,我应该把它放在状态下吗?
答案 0 :(得分:0)
class MomentCounter extends Component {
state = {
dateUpdate: moment().format(),
hourTimeDiff: null,
minuteTimeDiff: null,
}
handleUpdate = () => {
const nowMoment = moment();
this.getTimeDiff(nowMoment);
}
getTimeDiff = (nowMoment) => {
const updateMoment = moment(this.state.dateUpdate);
const hourTimeDiff = moment.duration(nowMoment.diff(updateMoment)).as("hours");
const minuteTimeDiff = moment.duration(nowMoment.diff(updateMoment)).as("minutes");
this.setState({
dateUpdate: moment(nowMoment).format(),
hourTimeDiff: Number(hourTimeDiff).toFixed(),
minuteTimeDiff: Number(minuteTimeDiff).toFixed(),
})
}
renderMomentDiff = () => {
if (!this.state.hourTimeDiff) {
return <div/>;
}
if (this.state.hourTimeDiff >= 1) {
return <div>{`${this.state.hourTimeDiff} hours and ${this.state.minuteTimeDiff} mins ago`}</div>;
}
return <div>{`${this.state.minuteTimeDiff} mins ago`}</div>;
}
render () {
return (
<div>
{this.renderMomentDiff()}
<button onClick={this.handleUpdate}>update</button>
</div>
);
}
}