我正在尝试开发一个简单的计时器游戏,用户需要在精确的毫秒内停止秒表。我继续使用设置间隔,只是后来才意识到这很重,会导致很多滞后并且无法正常运行。 有什么可以替代的呢? 这段代码在iPhone xs上可以正常工作,但是在android上却很难工作。我该如何解决这个问题? 这是我的代码:
class TimerGame extends Component {
_isMounted = false;
constructor(props) {
super(props);
this.interval = null;
this.state = {
msec: 0,
lapArray: [0, 0, 0, 0, 0],
turn: 0,
};
}
componentWillUnmount() {
this._isMounted = false;
clearInterval(this.interval);
}
componentDidMount() {
this._isMounted = true;
if (this._isMounted) {
this.interval = setInterval(() => {
if (this.state.msec <= 100) {
this.setState({
msec: this.state.msec + 1,
});
} else {
this.setState({
msec: 0,
});
}
}, 1);
} else {
clearInterval(this.interval);
}
}
handleLap = (msec) => {
let temp = this.state.lapArray;
temp[this.state.turn] = msec;
this.setState({ lapArray: temp, turn: this.state.turn + 1 });
};
render() {
return (
<Screen
style={{
backgroundColor: colors.dark,
alignItems: "center",
justifyContent: "space-between",
flex: 1,
}}
>
<TimerGoal />
<View style={{ alignItems: "center" }}>
<StepCircleList
turn={this.state.turn}
msec={this.state.msec}
data={this.state.lapArray}
/>
<ProgressCircle
percent={this.state.msec}
radius={120}
borderWidth={40}
color={colors.white}
shadowColor="#999"
bgColor={colors.dark}
>
<Text style={{ fontSize: 35, color: colors.white }}>
{this.state.msec}
</Text>
</ProgressCircle>
</View>
<StopButton onPressBtn={() =>
this.handleLap(this.state.msec)} />
</Screen>
);
}
}