javascript - React .map 不重新渲染

标签 javascript reactjs

我正在构建一个排序算法可视化工具,在我的返回中,我正在创建 div 来表示垂直条,在animatedBubbleSort() 中,我在超时时交换状态数组中的值,该数组正在排序,但我期望发生的是,每次使用 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>
);

}

最佳答案

这是因为您使用数组中元素的索引作为键。 React 使用 key 来决定重新渲染哪些元素;因为你的键总是按相同的顺序排列,React 不会更新任何内容。尝试:

{array.map((value) => {
    return (
        <div
            style={{ height: `${value * 2}px` }}
            className="array-bar"
            key={value}
        ></div>
    );
})}

参见https://reactjs.org/docs/lists-and-keys.html#keys了解更多,具体如下:

We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Check out Robin Pokorny’s article for an in-depth explanation on the negative impacts of using an index as a key. If you choose not to assign an explicit key to list items then React will default to using indexes as keys.

关于javascript - React .map 不重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60271440/

相关文章:

javascript - chrome 54 中默认使用前置摄像头的 webrtc

javascript - Mongoose : cannot access populated value

reactjs - 故事书:ReferenceError: Jest 未定义

javascript - 在 MongoDB 中存储 dataURL 以通过本地 URL (JS) 访问它

javascript - 定时动画 gif 显示

javascript - 如何实现这个plotly的例子?

javascript - 使用 Express.js 和 Node.js 的 Swig 条件扩展标签

javascript - babel-plugin-react-css-modules 不会更改样式标签中的类名

javascript - PreventDefault() 方法不阻止页面重新加载 ReactJS

javascript - 在react-native无状态组件中格式化多个props