[英]How to use Retun in a For-Loop without breaking out of the Loop (JS)?
我正在尝试从一个数组运行多个倒计时,例如 [11, 12, 13, 14, 15, 16]。 我想要实现的是第一次将倒计时时间设置为11,当它到达0时,定时器设置为12然后倒计时到0。之后,重置为13并倒计时,然后重置为14倒计时等
但是,我的代码只能从 11 倒数到 0,然后停止。 For 循环似乎不起作用,并且永远不会将第二项 12 放入计时器中。 后来我发现这是因为 for 循环内部的 retun 在循环之外破坏了它。 我想知道是否有一些聪明的方法可以避免在 For-Loop 中返回? 或者,如何在不跳出循环的情况下在 For-Loop 中使用 Return?
(我在那里有另一个计数器,称为 TotalTime,我打算计算它所花费的所有总时间,即 11+12+13+14 等)
定时器和显示屏:
import {View, Text, StyleSheet, FlatList} from 'react-native';
import PlaySounds from './PlaySounds';
const CustomTimer = ({time, length}) => {
const [seconds, setSeconds] = useState(time);
const [totalTime, setTotalTime] = useState(0);
useEffect(() => {
if (seconds > 0 )
{ const interval = setInterval(() => {
setSeconds(seconds => seconds - 1);
setTotalTime(seconds=>seconds + 1)
}, 1000);
return () => clearInterval(interval);
}}, [seconds])
return (
<View>
<Text style={{fontSize:20}}> Count Down: {seconds} sec</Text>
<Text style={{fontSize:20}}> Total Time: {totalTime} sec</Text>
</View>
)}
export default CustomTimer;
=====================
import React, {useEffect, useState} from 'react';
import {SafeAreaView,View,Button,ScrollView, Text, StyleSheet} from 'react-native';
import CustomTimer from '../component/CustomTimer';
const BrewScreen = () => {
const timeArray= [11, 12, 13, 14, 15, 16]
const length = timeArray.length
const countDownArray=() =>{
for (let i=0; i<length; i++) {
return(<CustomTimer time={timeArray[i]} length={length}/>)
}
}
return (
<>
<ScrollView>
{countDownArray()}
</ScrollView>
</>
)
}
问题似乎是您在 for 循环中返回。
这意味着在 countDownArray function 中 for 循环的第一次迭代期间,您将返回 Timer 元素。 执行此操作时,function 将退出,因此循环不会继续。
相反,您需要以不同的方式创建 Timer 元素来实现您想要的行为。 这可能需要在 Timer 元素中回调 function。 这可用于更新 BrewScreen 的 state,并更新显示的 Timer。
我终于解决了,不是使用循环,而是使用强大的 useEffect:
const CustomTimer = ({time}) => {
const [seconds, setSeconds] = useState(time[0]);
const [count, setCount] = useState(1)
const [totalTime, setTotalTime] = useState(0);
useEffect(() => {
if (seconds >= 0 )
{ const interval = setInterval(() => {
setSeconds(seconds => seconds - 1);
setTotalTime(seconds=> seconds + 1)
console.log('seconds ', seconds, ' totalTime ', totalTime)
}, 1000);
return () => clearInterval(interval);}
else if (count<(time.length)) {
setCount(count => count+1)
setSeconds(time[count])}
else return
}
)
return (
<View>
<Text style={{fontSize:20}}> Count Down: {seconds} sec</Text>
<Text style={{fontSize:20}}> Total Time: {totalTime} sec</Text>
{seconds===3?<PlaySounds/>:null}
</View>
)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.