我有一个存储为 prop 的数组:
constructor(props) {
super(props);
this.letters = [];
}
在 componentDidMount
方法中,我将这个 Prop 放在一个 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);
通过 this.letters
上的这两个 forEach
循环,我在 this.letters.forEach...
上得到了这个错误> 第二个循环的行:
TypeError: Cannot read property 'forEach' of undefined
我尝试将 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);
这行得通,但我不确定我是否理解为什么 this.letters
行不通?
我还尝试用 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 箭头作为将 this 绑定(bind)到函数的方式)。
setTimeout(function() {
-> setTimeout(() => {
关于javascript - this.prop 上的多个 forEach 语句导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56418442/