如何防止 <Clock/> 子组件在父属性更改时重置其状态

问题描述

我设计了一个非常简单的组件,它只是以 HH:MM 格式显示当前时间,每秒钟闪烁分号。

这个时钟被其他可能是直接父级的 HOC 使用。这个 HOC 组件本身依赖于每分钟都在变化的属性

当 HOC 属性更新时,HOC 本身也会更新,并且因此也会更新时钟

这使时钟重置(我的意思是状态重置为其初始值)使时钟呈现故障(即半秒破折号显示,替换当前时间)。

你将如何防止我的时钟重置?

function Clock() {
        const separator = '—'
        // = Blinking Time
        const [hour,setHour] = useState('')
        const [sep,_setSep] = useState(separator)
        function setSep(sep) {
            _setSep(sep)
            log(`setSep with "${sep}"`)
        }
        const [min,setMin] = useState('')

        const toggle = useRef(false)


        if (sep === separator) {
            console.warn('*** useState reset!')
        }

        const blinkTime = useCallback(() => {
            toggle.current = !toggle.current
            //console.log('clock toggle is ',toggle.current)
            const Now = Math.round(Date.Now()*1e-3)
            let time = OlenPEPS.dateTime.time({unixDate: Now})
            console.log('clock is: '+time)
            const times = time.split(':')
            setHour(times[0])
            setMin(times[1])
            setSep(toggle.current ? ':' : ' ')
        },[])

        // == On mount,setup timer callback
        useEffect(() => {
            console.log('mount')

            const timer = setInterval(blinkTime,0.5e3)
            return () => {
                clearInterval(timer)
                console.log('unmount')
            }
        },[])

        console.log('render',hour,sep,min)

        return (
        <h1 className="title">
            <strong><span>{hour}</span><div style={{display: 'inline-block',width:'0.5rem',textAlignment: 'center'}}>{sep}</div><span>{min}</span></strong>
        </h1>)
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)