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

时间:2021-02-25 10:57:01

标签: reactjs lifecycle

我设计了一个非常简单的组件,它只是以 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>)
}

0 个答案:

没有答案
相关问题