将毫秒相加可得出小时,分钟,秒和毫秒

时间:2019-05-14 19:48:13

标签: javascript reactjs

我正在尝试使用Reactjs将lapTime添加到totalLaptime状态。

我首先将时间设置为毫秒,即81300,它等于01:21:300(1分21秒300毫秒)。然后,我有一个按钮,其中onClick添加了新的lapTime,然后将lapTime添加到totalLapTime。 最后,我然后有了一个函数,该函数花费总毫秒数并将其转换为可读格式,即01:21:300。

我的状态是

  this.state = {
      lap: 0,
      lapTime: 0,
      totalLapTimes: 0,
      totalLapTimeCalc: ''
    };

我的点击功能可继续下一圈

handleClick = () => {
    this.setState(({lap, tyres, deg}) => ({
      lap: lap + 1,
      lapTime: this.randomLap(), <-- function makes a random milliseconds 
      totalLapTimes: + this.state.lapTime + this.state.totalLapTimes,
      totalLapTimeCalc: this.lapTimeCalc(this.state.totalLapTimes)
    }));
  };

将时间从毫秒转换为可读格式的函数:

lapTimeCalc = (ms) => {
    return new Date(ms).toISOString().slice(11, -1);
};

每次单击圈按钮后,预期结果应为01:21:xxx添加到totalLapTimeCalc中。

此刻,当我单击“圈”按钮时,我必须先单击3次,然后才能转换totalLapTime,然后,totalLapTimeCalc不正确。

1 个答案:

答案 0 :(得分:0)

您正在使用尚未设置的状态来计算您要设置的状态。

如果稍微更改点击处理程序,它将可以正常工作:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      lap: 0,
      lapTime: 0,
      totalLapTimes: 0,
      totalLapTimeCalc: ''
    };
  }

  handleClick = () => {

    const { lap, totalLapTimes } = this.state; 
    const lapTime = this.randomLap(); 
    const totalTime = totalLapTimes + lapTime;
    const totalCalc = this.lapTimeCalc(totalTime)

    this.setState({
      lap: lap + 1,
      lapTime,
      totalLapTimes: totalTime,
      totalLapTimeCalc: totalCalc,
    });
  };

  lapTimeCalc = (ms) => {
    return new Date(ms).toISOString().slice(11, -1);
  };

  randomLap = () => Math.floor(Math.random() * 100000) + 80000;


  render() {
    const { lap, lapTime, totalLapTimes, totalLapTimeCalc } = this.state;
    return (
      <div>
        <button onClick={this.handleClick}>Click Me</button>
        <p>Lap:{lap}</p>
        <p>Lap Time:{lapTime} ({this.lapTimeCalc(lapTime)})</p>
        <p>Total Lap Time:{totalLapTimes}</p>
        <p>Total Lap Time Calc:{totalLapTimeCalc}</p>
      </div>
    );
  }
}



ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>