私はReactでStopwatchアプリを実装しようとしていました。すべてが実装されており、現在動作しているように見えます。しかし、停止ボタンをクリックしてからボタンをもう一度押すと、NaNの結果がページに表示されます。この問題を解決する方法はありますか?StopwatchアプリでNaNを取得する反応
いくつかの点でデータ型をStringからNumberに変更する必要があると思います。問題を解決するためにNumber()を使用しようとしましたが、機能しませんでした。あなたがthis.timeToAdd
を参照し、あなたのhandleStop
方法で
import React from "react";
import { render } from "react-dom";
class Stopwatch extends React.Component {
constructor(props) {
super(props);
this.state = {
startTime: 0,
elapsedTime: 0,
timerId: null,
isRunning: false,
timeToAdd: 0
};
}
updateTimerText =() => {
const m = Math.floor(this.state.elapsedTime/60000);
const s = Math.floor((this.state.elapsedTime % 60000)/1000);
this.setState({
elapsedTime: m + ":" + s
});
};
countUp =() => {
this.setState({
timerId: setTimeout(() => {
// this.state.elapsedTime = Date.now() - this.state.startTime;
this.setState({
elapsedTime: Date.now() - this.state.startTime + this.state.timeToAdd
});
this.updateTimerText();
this.countUp();
}, 100)
});
this.state.timerId;
};
handleStart =() => {
if (this.state.isRunning === true) {
return;
}
this.setState({
isRunning: true
});
this.setState({
startTime: Date.now()
});
this.countUp();
};
handleStop =() => {
if (this.state.isRunning === false) {
return;
}
this.setState({
isRunning: false
});
this.setState({
timeToAdd: this.timeToAdd + (Date.now() - this.state.startTime)
});
clearTimeout(this.state.timerId);
};
handleReset =() => {
if (this.state.isRunning === true) {
return;
}
this.setState({
elapsedTime: 0
});
};
render() {
return (
<div>
<div>{this.state.elapsedTime}</div>
<button onClick={this.handleStart}>Start</button>
<button onClick={this.handleStop}>Stop</button>
<button onClick={this.handleReset}>Reset</button>
</div>
);
}
}
render(<Stopwatch />, document.getElementById("root"));
'elapsedTime:m +": "+ s"は文字列ですが、この状態プロパティは数字として扱われます。 'handleStop'には' timeToAdd:this.timeToAdd'がありますが、izはおそらく 'this.state.timeToAdd'です。 –