在下面的代码中,我通过console.log记录songList的状态。想象一下,如果点击了 3 首歌曲,代码中的第一个 console.log 会输出一个包含 3 个对象的数组。每次倒计时后触发第二个console.log,显示songList的状态。再次,假设我点击了 3 首歌曲。 SongList 状态的第一个 console.log 输出:[{...}, {...}, {...}] 然后每次倒计时后,songList状态的第二个console.log输出:1st countdown [{...}], 2nd countdown [{...}, {...}], 3rd countdown [{...} , {...}, {...}]。
我怀疑输出会是:第一次倒计时 [{...}, {...}, {...}], 第二次倒计时 [{...}, {...}, { ...}],第三次倒计时 [{...}, {...}, {...}]
songList 的状态如何变化?
注意:songList状态是作为prop传入的,改变songList状态的函数(setSongList)也传入了,但代码中没有调用。
const Countdown = ({ songList, setSongList }) => {
const [timerHours, setTimerHours] = useState(0);
const [timerMinutes, setTimerMinutes] = useState(0);
const [timerSeconds, setTimerSeconds] = useState(0);
console.log(songList) //if 3 songs clicked, output [{},{},{}]
let interval = null;
const timer = (songList) => {
const songTime = somgList.length * 5 * 60 * 30;
const futureTime = new Date().getTime() + songTime;
if (songTime > 0) {
interval = setInterval(() => {
const timeNow = new Date().getTime();
const waitTime = futureTime - timeNow;
const hours = some calculations
const minutes = some calculations
const seconds = some calculations
if (hours && minutes && seconds <= 0) {
console.log(songList);
//issue is here assuming I clicked 3 songs
//actual output after countdown for each hour,min,sec <= 0
//output [{}]
//output [{},{}]
//output [{},{},{}]
//my expectations is
//output [{},{},{}]
//output [{},{},{}]
//output [{},{},{}]
clearInterval(interval);
} else {
setTimerHours(hours);
setTimerMinutes(minutes);
setTimerSeconds(seconds);
}
}, 1000);
}
};
useEffect(() => {
timer(songList);
return () => {
clearInterval(interval);
};
}, []);
};