我有一栏作为时间,另一栏作为计时器。在时间列中,我有一个请求创建时间,在计时器列中,我想将计时器从请求创建时间设置为当前IST时间。
就像如果我的创建时间为 1562307956195 ,那么我希望我的计时器为 15h20m ,并且每秒钟增加一次。
表有点像这样
<Table>
<thead>
<tr>
<th>Creation Time</th>
<th>Time Spent</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>1562307956195 </td>
<td> 15H30M</td>
</tr>
<tr>
<td>1562307956195 </td>
<td> 15H30M</td>
</tr>
</tbody>
</Table>
我想为每一行计时。我没有弄清楚如何动态地做到这一点。
我尝试过:
state = {
timer: 0,
hours: 0,
minutes: 0,
seconds: 0
};
timer = (unix_timestamp) => {
console.log('ts', unix_timestamp)
var difference = unix_timestamp - Date.now();
var hoursDifference = Math.floor(difference/1000/60/60);
difference -= hoursDifference*1000*60*60
var minutesDifference = Math.floor(difference/1000/60);
difference -= minutesDifference*1000*60
var secondssDifference = Math.floor(difference/1000);
difference -= secondssDifference*1000*60
this.setState({ hours: hoursDifference })
this.setState({ minutes: minutesDifference })
this.setState({ seconds: secondssDifference })
console.log(d)
return this.state.minutes + ':' + this.state.seconds
}
<Table>
<thead>
<tr>
<th>Creation Time</th>
<th>Time Spent</th>
</tr>
</thead>
<tbody>
{this.state.serviceRequests.map((request,index) => (
<tr key={index}>
<td> {this.getDate(request.createdAt)} </td>
<td> {this.timer(request.createdAt)} </td>
</tr>
))}
</tbody>
</Table>
答案 0 :(得分:2)
您只需要一个计时器组件。设置startTime
并声明。然后使用类似updateTime
函数的状态更新状态
class Timer extends Component {
constructor(p) {
super(p)
this.interval = p.interval || 1000
this.startTime = p.ts
this.state = {
ts: new Date().valueOf()
}
}
componentDidMount() {
this.timer = setInterval( () => {
this.updateTime()
}, this.interval)
}
updateTime = () => {
this.setState({ts: new Date().valueOf()})
}
getFormattedTime = () => {
return moment(this.startTime).fromNow()
}
render() {
return (
<tr>
<td> {moment(this.startTime).format('MMM Do YY')} </td>
<td> {this.getFormattedTime()} </td>
</tr>
)
}
}
那么您的用法将是这样
{this.state.serviceRequests.map(
(request,index) => <Timer ts={request.createdAt} key={request.id} />
}
我不太喜欢为一般用例计时器呈现诸如<tr>
之类的特定元素。因此,也许传递一个render函数作为道具,这样您就可以指定应该如何渲染时间。但这就是您的重构:)
编辑
答案 1 :(得分:-1)
如果我理解正确,那么您想计算从创建请求到当前时间的时间。
您可以使用moment toNow()方法。
在此官方文档页面中阅读更多内容。 toNow()