我试图在窗口加载时从数字 0 开始 if 语句,但它忽略了 0 并从 1 开始,有人可以帮助我理解这是如何工作的吗。
showAnime = () => {
let counter = 0;
setInterval(() => {
counter++;
if (counter === 0) {
console.log(counter);
// when window is loaded this condition should start first
this.setState({
animateRightOne: "animated fadeInRightBig delay-one"
});
} else if (counter === 1) {
console.log(counter);
this.setState({
animateRightTwo: "animated fadeInRightBig delay-two"
});
} else if (counter === 2) {
console.log(counter);
this.setState({
animateRightThree: "animated fadeInRightBig delay-three"
});
} else if (counter === 3) {
console.log(counter);
this.setState({
animateLeftFour: "animated fadeInLeftBig delay-four"
});
} else if (counter === 4) {
console.log(counter);
this.setState({
animateRightFive: "animated fadeInRightBig delay-five"
});
} else if (counter === 5) {
console.log(counter);
this.setState({
animateRightSix: "animated fadeInRightBig delay-six"
});
} else if (counter === 6) {
counter = 0;
}
}, 7000);
};
最佳答案
只需将 counter++
放在函数末尾即可:
showAnime = () => {
let counter = 0;
setInterval(() => {
/* */
} else if (counter === 5) {
console.log(counter);
this.setState({
animateRightSix: "animated fadeInRightBig delay-six"
});
} else if (counter === 6) {
counter = 0;
}
counter++;
}, 7000);
};
通过将每个句子存储到一个数组中,然后从中选出当前句子,您可以大大减少代码。
并且,要自动循环句子,您可以使用模数 %
而不是将计数器设置为 0:
showAnime = () => {
let counter = 0;
setInterval(() => {
const sentences = [
"animated fadeInRightBig delay-one",
"animated fadeInRightBig delay-two",
"animated fadeInLeftBig delay-three",
"animated fadeInRightBig delay-five",
"animated fadeInRightBig delay-six"
]
this.setState({
animateRightOne: sentences[counter % 6]
});
counter++;
}, 7000);
};
更短:
showAnime = () => {
let counter = 0;
setInterval(() => {
const sentences = [["one", 'Right'], ["two", 'Right'], ["three", 'Left'], ["five", 'Right'], ["six", 'Right'] ]
const [num, side] = sentences[counter % 6]
this.setState({
animateRightOne: `animated fadeIn${side}Big delay-${num}`
});
counter++;
}, 7000);
};
关于javascript - 如何在Interval React.js中乘以数字时获得索引0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54705142/