在部署到应用商店以对我的应用进行Beta测试时,我无法使某些事件和功能完全按时触发。我的应用程序是一个简单的点生成器,每分钟生成一个点,但是,直到启动计时器三分钟后才开始生成点。我正在使用setInterval和setTimeout,并认为它们之间可能玩得不好。
export default class GeoAndMoments extends React.Component {
constructor(props) {
super(props)
this.didMount = false
this.state = {
storedPoints: 0 //pulled from an external database
}
componentDidMount() {
this.setState({isLoaded: true})
this.didMount = true
}
componentWillUnmount() {
clearInterval(this.intervalId)
this.didMount = false
}
timer() {
this.setState({
counter: moment().diff(this.state.startingMoment, 'minutes'),
storedAndCounter: moment().diff(this.state.startingMoment, 'minutes') + this.state.storedPoints,
})
}
render() {
if(!this.state.isShown){
setTimeout(() => {
this.watchId = navigator.geolocation.watchPosition(
(position) => {
if(position.coords.speed >= 10) {
this.setState({
speed: position.coords.speed,
isShown: true,
startingMoment: moment(),
counter: moment().diff(this.state.startingMoment, 'minutes')
})
this.setState({
storedAndCounter: moment().diff(this.state.startingMoment, 'minutes') + this.state.storedPoints,
})
}
},
{ enableHighAccuracy: true, timeout: 21000, maximumAge: 1000, distanceFilter: 10 },
)
}, 10000)
this.intervalId = setInterval(this.timer.bind(this), 60000)
clearTimeout()
}
return (
<Container>
<Container>
{this.state.isShown && <Container>
<Content>
{this.state.isLoaded ? <Text>Welcome {this.state.email}</Text> : null}
<Text
>Points Earned This Trip</Text>
<ImageBackground
source={require('../public/odometer.jpg')}
>
<Text
>{this.state.counter}</Text>
</ImageBackground>
<Text
>Total Points Earned</Text>
<ImageBackground
source={require('../public/odometer.jpg')}
>
{this.state.isLoaded ? <Text>{this.state.storedAndCounter}</Text> : <Text>Loading...</Text>}
</ImageBackground>
</Content>
</Container>}
<Logo />
</Container>
<Feedback />
</Container>
)
}
}
setTimeout的目的是确保用户移动的速度超过10MPH,并创建setInterval。