You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJs 表格每行计时器运行异常,该如何修复?

现有代码的核心问题

  1. 你定义的mycount是普通变量,没有存在React组件的state中,修改后不会触发组件重渲染,所以页面的计时不会更新
  2. 没有启动定时任务,现有写法只在组件渲染时执行一次item--,之后不会自动倒计时
  3. timerInt方法里遍历了整个mycount数组,导致每行都会输出所有倒计时值拼接的结果,就是你截图里一行出现两个时间串的问题
  4. 调用timerInt时没有传入行的索引,无法匹配每行对应的倒计时数值

修复方案

  1. 把倒计时数值存在组件state中,挂载时启动定时器每秒更新
  2. 渲染时按行索引取值,不要遍历整个数组
  3. 组件卸载时清除定时器避免内存泄漏

类组件完整示例代码:

class YourTableComponent extends React.Component {
  // 初始化倒计时到state
  state = {
    mycount: [7200, 3600]
  }

  componentDidMount() {
    // 每秒更新一次倒计时
    this.timer = setInterval(() => {
      this.setState(prev => ({
        mycount: prev.mycount.map(item => item > 0 ? item - 1 : 0)
      }))
    }, 1000)
  }

  componentWillUnmount() {
    // 卸载时清定时器
    clearInterval(this.timer)
  }

  // 格式化时间的方法,传入当前行对应的倒计时值
  formatTime = (second) => {
    return new Date(second * 1000).toISOString().substr(11,8)
  }

  // 表格列配置
  columns = [
    {
      title: 'Time ',
      dataIndex: 'project_time',
      key: 'project_time',
      render: (text, record, index) => this.formatTime(this.state.mycount[index])
    },
    // 其他列配置...
  ]

  render() {
    return <Table columns={this.columns} dataSource={你的表格数据源} />
  }
}

函数组件完整示例代码:

import { useState, useEffect } from 'react'

const YourTableComponent = () => {
  const [mycount, setMycount] = useState([7200, 3600])

  useEffect(() => {
    const timer = setInterval(() => {
      setMycount(prev => prev.map(item => item > 0 ? item -1 : 0))
    }, 1000)
    return () => clearInterval(timer)
  }, [])

  const formatTime = (second) => {
    return new Date(second * 1000).toISOString().substr(11,8)
  }

  const columns = [
    {
      title: 'Time ',
      dataIndex: 'project_time',
      key: 'project_time',
      render: (text, record, index) => formatTime(mycount[index])
    },
    // 其他列配置
  ]

  return <Table columns={columns} dataSource={你的表格数据源} />
}

内容的提问来源于stack exchange,提问作者fazal abbas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 10:30:02