Javascript 此.prop上的多个forEach语句导致错误
我有一个数组存储为道具:Javascript 此.prop上的多个forEach语句导致错误,javascript,reactjs,Javascript,Reactjs,我有一个数组存储为道具: constructor(props) { super(props); this.letters = []; } 在componentDidMount方法中,我将此道具放在forEach循环中,该循环中有一个setTimeout: componentDidMount() { this.letters.forEach((letter, index) => { setTimeout(function() {
constructor(props) {
super(props);
this.letters = [];
}
在componentDidMount
方法中,我将此道具放在forEach
循环中,该循环中有一个setTimeout
:
componentDidMount() {
this.letters.forEach((letter, index) => {
setTimeout(function() {
letter.classList.add('stroke');
}, index * 125);
});
}
这与预期的一样,向prop数组中的每个元素添加一个类
然后我尝试在这个循环之后添加第二个forEach
循环。这看起来有点混乱,但它基本上与第一个forEach
循环相同,但它被包装在setTimeout
中,因此它会在1秒后启动:
this.letters.forEach((letter, index) => {
setTimeout(function() {
letter.classList.add('stroke');
}, index * 125);
});
setTimeout(function() {
this.letters.forEach((letter, index) => {
setTimeout(function() {
letter.classList.add('fill');
}, index * 125);
});
}, 1000);
通过将这两个forEach
循环连在this.letters
上,我在第二个循环的this.letters.forEach…
行上得到了这个错误:
TypeError:无法读取未定义的属性“forEach”
我尝试将this.letters
设置为componentDidMount
中的另一个变量,并使用该变量而不是this.letters
:
const letters = this.letters;
letters.forEach((letter, index) => {
setTimeout(function() {
letter.classList.add('stroke');
}, index * 125);
});
setTimeout(function() {
letters.forEach((letter, index) => {
setTimeout(function() {
letter.classList.add('fill');
}, index * 125);
});
}, 1000);
这是可行的,但我不确定我是否理解为什么这个字母不起作用
我还尝试用letters
变量代替this.letters
——第一个循环可以使用this.letters
,但第二个循环无论如何都不能使用this.letters
const letters = this.letters;
letters.forEach((letter, index) => {
setTimeout(() => {
letter.classList.add('stroke');
}, index * 125);
});
setTimeout(function() {
letters.forEach((letter, index) => {
setTimeout(() => {
letter.classList.add('fill');
}, index * 125);
});
}, 1000);
问题在于箭头(react使用es6箭头将其绑定到函数)
setTimeout(函数(){
->setTimeout(()=>{
setTimeout(()=>{this.letters.forEach((letter,index)=>{setTimeout(function(){letter.classList.add('fill');},index*125);});},1000);
使用胖箭头函数访问父作用域的此
。该死——就是这样。我已经阅读了一些关于胖箭头函数的内容,以及它们如何与此
配合使用,但还没有完全掌握。我现在明白了。谢谢!不是重复的,但请查看更多信息。谢谢,看一看