繁体   English   中英

如何使用 react-compound-timer getTime() 方法更新组件 state

[英]How to update component state with react-compound-timer getTime() method

我正在创建一个组件来跟踪执行任务所需的时间。 我正在使用react-compound-timer来做到这一点。

我遇到的问题是单击“停止”按钮时无法更新组件 state。

这是代码:

import React, { useState } from 'react';
import Timer from 'react-compound-timer'
import clock from '../../../assets/images/clock-regular.svg'
import playIcon from '../../../assets/images/play.svg';
import pauseIcon from '../../../assets/images/pause.svg';
import stopIcon from '../../../assets/images/stop.svg';
import resetIcon from '../../../assets/images/reset.svg';

const LogTimer = () => {
  const [timerValue, setTimerValue] = useState(null);

  return (
    <Timer
      formatValue={(value) => `${(value < 10 ? `0${value}` : value)}`}
      initialTime={0}
      startImmediately={false}
      onStart={() => console.log('onStart')}
      onPause={() => console.log('onPause')}
      onStop={(value) => {
        setTimerValue(value);
        console.log('onStop')
      }}
      onReset={() => console.log('onReset')}
>
    {({ start, pause, stop, reset, getTime }) => 
      ( 
        <>
          <div className="d-flex align-items-center justify-content-between">
            <div className="d-flex align-items-center">
              <img src={clock} alt="clock" className="pr-2" style={{ width: '1.75rem' }}/><Timer.Hours />:<Timer.Minutes />:<Timer.Seconds /> 
            </div>
          </div>
          <div className="d-flex justify-content-between" style={{ minWidth: '9rem' }}>
            <img src={playIcon} className="control-btn" alt='play' role='button' onClick={start}></img>
            <img src={pauseIcon} className="control-btn" alt='pause' role='button' onClick={pause}></img>
            <img src={stopIcon} className="control-btn" alt='stop' role='button' onClick={
              () => {
                const actualTime = getTime();
                stop(actualTime);
              }
              }></img>
            <img src={resetIcon} className="control-btn" alt='reset' role='button' onClick={reset}></img>
          </div>
        </>
    )}
</Timer>
  )
}

export default LogTimer;

如果我登录到控制台'actualTime',它在单击停止按钮时正确地具有 getTime() 方法的值。

但是组件 state 没有更新。 我尝试了其他几种潜在的解决方案,例如尝试通过道具“setTimerValue”function,但它不起作用。

我该如何解决这个问题?

谢谢你的时间。

您的问题是您通过 stop 发送实际时间是不可能的, stop 只是一种通知 Timer 停止的方法,因此您无法向其发送参数。 更新您的代码如下:

<img
      className="control-btn"
      alt="stop"
      role="button"
      onClick={() => {
      const actualTime = getTime();
      setTimerValue(actualTime);
      stop();
     }}
/>

还可以使用 useEffect 查看更新的值:

useEffect(() => {
    console.log("timerValue: " + timerValue);
}, [timerValue]);

我的代码框链接以查看更新的代码: https://codesandbox.io/s/react-hooks-counter-demo-o5ebq?file=/src/Timer.js

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM