问题描述
使用Create-React-App []
Building a Sort-Visualizer in React using the Create-React-App [https://roy-05.github.io/sort-visualizer/ ]
我正在使用setTimeouts为循环的每次迭代设置动画。在开发人员控制台上,我收到以下警告:
I'm animating each iteration of the loop using setTimeouts. On dev console I get the following warning:
下面是代码段:
for(let i=0; i<arr.length-1; i++){
let minimum = i; //Declare minimum here
setTimeout(()=>{
for(let j = i+1; j<arr.length; j++){
setTimeout(()=>{
//Getting a warning for these references:
array_bar[j].style.backgroundColor = 'red';
array_bar[minimum].style.backgroundColor = 'blue';
setTimeout(()=>{
if(arr[j] < arr[minimum]){
array_bar[minimum].style.backgroundColor = 'lightblue';
minimum = j;
}
else{
array_bar[j].style.backgroundColor = 'lightblue';
}
}, 4);
}, (j-1)*4);
}
通过,我相信问题可能是我正在修改setTimeout内部的值,但是
Going through ESLint Docs, I believe the issue might be that i'm modifying the value inside the setTimeout but the variable is declared outside its scope.
我不确定如何解决该警告,我们将不胜感激!
I'm not sure how to fix that warning, any help will be appreciated!
注意:这是您需要的全部功能-
Note: Here's the entire function if you need it -
selectionSort(){
const arr = this.state.array,
array_bar = document.getElementsByClassName("array-elem");
this.setState({startedSelectionSort: true});
for(let i=0; i<arr.length-1; i++){
let minimum = i; //Declare minimum here
setTimeout(()=>{
for(let j = i+1; j<arr.length; j++){
setTimeout(()=>{
//Getting a warning for these references:
array_bar[j].style.backgroundColor = 'red';
array_bar[minimum].style.backgroundColor = 'blue';
setTimeout(()=>{
if(arr[j] < arr[minimum]){
array_bar[minimum].style.backgroundColor = 'lightblue';
minimum = j;
}
else{
array_bar[j].style.backgroundColor = 'lightblue';
}
}, 4);
}, (j-1)*4);
}
setTimeout(()=>{
let temp = arr[i],
arr1_height = arr[minimum],
arr2_height = arr[i];
arr[i] = arr[minimum];
arr[minimum] = temp;
array_bar[i].style.height = `${arr1_height}px`;
array_bar[minimum].style.height = `${arr2_height}px`;
array_bar[i].style.backgroundColor = "green";
if(i !== minimum){
array_bar[minimum].style.backgroundColor = 'lightblue';
}
}, 400);
if(i === arr.length-2){
setTimeout(()=>{
array_bar[i+1].style.backgroundColor = "green";
},800);
}
}, i*400);
}
setTimeout(()=>{
this.setState({sorted: true})
}, arr.length*400+1750);
}
推荐答案
我也遇到同样的警告。就我而言,我在迭代之外声明了变量,但在 forEach
方法中声明了变量。
I also encountered same warning. In my case, I declared variable outside the iteration, but modified variable inside forEach
method.
类似以下内容:
// some code above
let validInputs = true;
someInputs.forEach( input => {
validInputs = input.value && validInputs;
})
我做了一些重新研究后,在这篇文章中发现了,提到 JSHint不会就像如何一遍又一遍地重新创建其中的匿名功能。
我更改了 forEach
指向的箭头函数(让索引i = 0;索引< someInputs.length;索引++)
,警告消失了。
也许在您的情况下,将 setTimeout
更改为传统的非箭头功能可以删除警告。
Perhaps in your case, change setTimeout
to traditional non-arrow function can remove the warning.
这篇关于调试:ESLint警告“在循环中声明的函数包含对变量的不安全引用... no-loop-func”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!