我正在构建一个排序算法可视化程序,在我的返回值中,我创建div来表示垂直条形图。在animatedBubbleSort()函数中,我使用setTimeout()函数交换状态数组中的值。虽然数组已经被排序,但我原本期望的是每次使用updateArray()更改状态时.map函数会重新渲染。但是.map函数根本没有重新触发。
import React, { useState } from "react";
import "../styles/App.css";
import { Header } from "./Header";
export default function SortingVisualizer(props) {
const LOWER_BOUND = 5;
const UPPER_BOUND = 200;
const ARRAY_SIZE = 200;
const [array, updateArray] = useState(fillArrayWithRandomValues);
// returns a random number between bounds inclusive
function randomNumberBetweenBounds() {
return Math.floor(Math.random() * UPPER_BOUND) + LOWER_BOUND;
}
// fills array with random values
function fillArrayWithRandomValues() {
let tempArray = [];
for (let i = 0; i < ARRAY_SIZE; i++) {
tempArray.push(randomNumberBetweenBounds());
}
return tempArray;
}
function animatedBubbleSort() {
let tempArr = array;
let len = tempArr.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
if (tempArr[j] > tempArr[j + 1]) {
let tmp = tempArr[j];
tempArr[j] = tempArr[j + 1];
tempArr[j + 1] = tmp;
setTimeout(() => {
updateArray(tempArr);
}, 300 * i);
}
}
}
}
return (
<div>
<Header bubbleSort={animatedBubbleSort} />
<div className="array-container">
{array.map((value, idx) => {
return (
<div
style={{ height: `${value * 2}px` }}
className="array-bar"
key={idx}
></div>
);
})}
</div>
</div>
);
key
来确定重新渲染哪些元素,但是因为您的键始终以相同的顺序出现,所以React 不会更新任何内容。尝试使用“值”作为您的键。 - Hamms