我有一列作为时间,另一列作为计时器。在时间列中,我有一个请求创建时间,在计时器列中,我想将计时器从请求创建时间设置为当前 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>
最佳答案
您只需要一个计时器组件。设置 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>
这样的特定元素对于一般用例计时器。所以也许传递一个渲染函数作为 Prop ,这样你就可以指定应该如何渲染时间。但这对你来说是一个重构:)
编辑
关于javascript - 动态表每一行的定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56929200/