javascript - 动态表每一行的定时器
问题描述
我有一列作为时间,另一列作为计时器。在时间列中,我有一个请求创建时间,在计时器列中,我想将计时器从请求创建时间设置为当前 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>
一般用例计时器。因此,也许可以将渲染函数作为道具传递,这样您就可以指定应该如何渲染时间。但这对你来说是一个重构:)
编辑
推荐阅读
- npm - 为客户提供私人 npm
- sql - 如何在 SQL 中实现循环?
- unity3d - 以编程方式控制 Oculus Quest 相机直通模式
- javascript - 如何使用函数的参数来使用对象的数据?
- django - (admin.E116) 'list_filter[3]' 的值指的是 'groups',而不是指一个 Field
- python - 为什么这在 IDE 中有效,但在 CMD 提示符中无效?
- android - Android Firebase 身份验证永远重新创建活动
- ruby-on-rails - 在 Rails 5 中使用带有自引用资源的 form_with
- python - 如何使用 Python 和 Win32 制作网页浏览器自动化工具
- python - 为什么 Python 3.7 没有 Python 3.6 那样的键盘模块?