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

React点击按钮记录时间数组失效问题排查与实现需求

问题原因
  • startTime是组件内部的普通变量,每次组件重新渲染(比如setTime更新当前时间时),这个变量都会被重新初始化为空数组,之前push进去的内容会直接丢失。
  • React不会监听普通变量的变化,就算你往startTime里push了数据,也不会触发组件重新渲染,页面上根本看不到更新后的列表。
修复方案

1. 将startTime改为React状态变量

用useState管理点击时间数组,让React追踪数组变化,更新时自动触发组件渲染。

2. 修复定时器逻辑

原代码的setTimeout只执行一次,无法实现每秒更新时间的效果,换成setInterval并在组件卸载时清理定时器,避免内存泄漏。

3. 完善列表展示

补充表格的tbody部分,遍历startTime数组渲染每一条点击时间记录。

完整修复代码

import React, { useEffect, useState } from 'react'

function Clock() {
    const [time, setTime] = useState(new Date().toLocaleTimeString())
    const [isHydrated, setIsHydrated] = useState(false);
    // 用useState管理点击时间数组
    const [startTime, setStartTime] = useState([]);

    useEffect(() => {
        setIsHydrated(true);
        // 用setInterval实现每秒更新当前时间
        const timer = setInterval(() => {
            setTime(new Date().toLocaleTimeString())
        }, 1000);
        // 组件卸载时清理定时器
        return () => clearInterval(timer);
    }, [])

    if (!isHydrated) {
        return null;
    }

    const updateElement = (currentTime) => {
        // 函数式更新,基于最新数组状态添加新时间
        setStartTime(prevTimes => [...prevTimes, currentTime]);
    }

    return (
        <div>
            <div className='container flex flex-col'>
                <h1 className="text-red-500 p-10">Productivity app</h1>

                <div>
                    <div>
                        <span className='p-5 font-bold'>time : {time}</span>
                    </div>

                    <button
                        onClick={() => updateElement(new Date().toLocaleTimeString())}
                        className='bg-red-500 hover:bg-red-700 p-10 w-2/5 text-white rounded-full'>Start</button>

                </div>

                <div className="overflow-x-auto relative mt-5">
                    <table className="w-full text-sm text-left text-gray-500 dark:text-gray-400">
                        <thead className="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
                            <tr>
                                <th scope="col" className="py-3 px-6">点击时间</th>
                            </tr>
                        </thead>
                        <tbody>
                            {/* 遍历数组渲染每条记录 */}
                            {startTime.map((item, index) => (
                                <tr key={index} className="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
                                    <td className="py-4 px-6">{item}</td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    )
}

export default Clock

关键细节

  • 用setStartTime(prevTimes => [...prevTimes, currentTime])这种函数式更新,确保每次都是基于最新的数组状态添加数据,避免异步更新导致的丢失。
  • 清理定时器是React组件的标准操作,防止组件卸载后定时器持续运行造成内存泄漏。
  • 给列表项添加key属性,帮助React高效识别元素变化,提升渲染性能。

内容的提问来源于stack exchange,提问作者Pj Here

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:15:16