我创建了一个页面,每隔5秒请求一次API,当有新数据时,它会导航到另一个屏幕,但它没有停止循环,我注意到它继续发出请求。我希望循环每5秒或10秒运行一次,当它导航到另一个页面停止时,每个请求之间也必须有一个超时(几秒)。
下面是我的代码:
function SearchForAMatch( {navigation, route}) {
useEffect(() => {
const interval = setInterval(() => {
let ew = ''
fetch('https://SomeAPIWebsite/getrooms')
.then(response => response.text())
.then(data => {
ew = data.split("\n");
for(let i = 0; i < ew.length - 1; i++)
{
if(ew[i].split('(')[0] == route.params?.region && ew[i].split('(')[2].split('/')[1] == route.params?.players && ew[i].split('(')[2].split('/')[0] != ew[i].split('(')[2].split('/')[1])
{ // new information! navigate to 'JoinRoom' screen
navigation.navigate('JoinRoom', {row: i});
}
}
})
}, 5000);
return () => clearInterval(interval);
}, []);
return (
<ImageBackground source={image} style={styles.backgroundImage}>
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{fontSize: hp('3%'), color: 'white', padding: 5, textAlign: 'center'}}>{route.params?.players}</Text>
</View>
</ImageBackground>
);
}发布于 2020-09-23 01:54:14
也许只需在导航行之后有数据时清除间隔即可。
{ // new information! navigate to 'JoinRoom' screen
navigation.navigate('JoinRoom', {row: i});
clearInterval(interval);
}https://stackoverflow.com/questions/64013744
复制相似问题