【发布时间】:2020-09-09 08:11:33
【问题描述】:
我正在为 React 中的快速排序算法可视化器制作动画。虽然我的代码不是最终的并且我仍在处理它,但我收到了“TypeError: Cannot read property 'style' of undefined”错误。我正在用这个项目学习 React,但不知道是什么导致了这个错误。错误来自这一行: const barOneStyle = arrayBars[barOneIndex].style;
quickSort() {
const animations = getQuickSortAnimations(this.state.array);
for (let i = 0; i < animations.length; i++) {
const isColorChange = animations[i][0] === "comparision1" || animations[i][0] === "comparision2";
const arrayBars = document.getElementsByClassName('array-bar');
if(isColorChange === true) {
const [comparision, barOneIndex, barTwoIndex] = animations[i];
const color = (animations[i][0] === "comparision1") ? 'navy' : 'pink';
const barOneStyle = arrayBars[barOneIndex].style;
const barTwoStyle = arrayBars[barTwoIndex].style;
setTimeout(() => {
barOneStyle.backgroundColor = color;
barTwoStyle.backgroundColor = color;
},i * ANIMATION_SPEED_MS);
}
else {
const [barIndex, newHeight] = animations[i];
if (barIndex === -1) {
continue;
}
const barStyle = arrayBars[barIndex].style;
setTimeout(() => {
barStyle.height = `${newHeight}px`;
},i * ANIMATION_SPEED_MS);
} }
//this.setState({array: sortArray})
//const RESTORE_TIME = parseInt(ANIMATION_SPEED_MS*animations.length/2 + 3000);
//setTimeout(() => this.restoreStoreButtons(), RESTORE_TIME);
}
我在同一个项目中没有收到合并排序的这个错误:
mergeSort() {
const animations = getMergeSortAnimations(this.state.array);
for (let i= 0; i < animations.length; i++) {
const arrayBars = document.getElementsByClassName('array-bar');
const isColorChange = i % 3 !== 2;
if (isColorChange) {
const [barOneIdx, barTwoIdx] = animations[i];
const barOneStyle = arrayBars[barOneIdx].style;
const barTwoStyle = arrayBars[barTwoIdx].style;
const color = i% 3 === 0 ? 'navy' : 'pink';
setTimeout(() => {
barOneStyle.backgroundColor = color;
barTwoStyle.backgroundColor = color;
}, i * ANIMATION_SPEED_MS);
} else {
setTimeout(() => {
const [barOneIdx, newHeight] = animations[i];
const barOneStyle = arrayBars[barOneIdx].style;
barOneStyle.height = `${newHeight}px`;
}, i * ANIMATION_SPEED_MS);
}
}
}
【问题讨论】:
标签: javascript arrays reactjs algorithm quicksort