首页 > 解决方案 > 动态表每一行的定时器

问题描述

我有一列作为时间,另一列作为计时器。在时间列中,我有一个请求创建时间,在计时器列中,我想将计时器从请求创建时间设置为当前 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>

标签: javascriptreactjs

解决方案


您只需要一个计时器组件。设置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>一般用例计时器。因此,也许可以将渲染函数作为道具传递,这样您就可以指定应该如何渲染时间。但这对你来说是一个重构:)

编辑

这是一个活生生的例子


推荐阅读