有什么方法可以优化这个可能有数百万组件渲染的react应用程序



以下是它的作用示例:https://ostralyan.github.io/flood-fill/

此应用程序用于教育目的,以下是源代码。

现在,任何大于100x100网格的东西都会给我带来性能问题。当我说性能问题时,我的意思是当我单击一个单元格时,它会延迟几秒钟,然后才会呈现下一个状态。我的目标是对其进行优化,以支持1米见方(1000x1000(。

这是我用于这种方法的算法

floodFillIterative(i, j) {
const oldColor = this.props.squares[i][j].color;
const newColor = this.getUniqueRandomColor(oldColor);
const squares = this.props.squares.slice();
const stack = [
[i, j]
];
while (stack.length) {
const squareCoordinates = stack.pop();
let newI = squareCoordinates[0];
let newJ = squareCoordinates[1];
if (newI < 0 || newI >= this.props.squaresPerRow) continue;
if (newJ < 0 || newJ >= this.props.squaresPerRow) continue;
let nextSquare = squares[newI][newJ];
if (nextSquare.color !== oldColor) continue;
if (nextSquare.visited) continue;
Array.prototype.push.apply(stack, [
[newI - 1, newJ],
[newI + 1, newJ],
[newI, newJ - 1],
[newI, newJ + 1],
]);
nextSquare.visited = true;
nextSquare.color = newColor;
}
this.setState({ squares });
this.clearVisisted(squares);
}

这个算法在线性时间内运行,所以我不确定优化算法是否真的会提高性能。尽管我对任何优化建议都持开放态度。

我这里还有一行代码

shouldComponentUpdate(nextProps) {
if (nextProps.color !== this.props.color) {
return true;
}
return false;
}

这样可以防止方块在没有任何变化的情况下重新绘制。我正在寻找任何其他方法来优化这个应用程序。

谢谢!

巨大的优化挑战!主要问题是每个Square都是一个react组件,因此您要创建大量的元素来在DOM中进行渲染。

在这种情况下,React自然会慢下来,即使在使用像Redux或shouldComponentUpdate这样的东西时也是如此。

我强烈建议使用HTML Canvas创建一个单独的组件来进行板渲染,而不是方形组件。

这里有一个伟大的代码笔,它可以实时渲染大量像素:function drawAll()https://codepen.io/gunderson/full/EyXBrr

这里有一个关于在画布上制作木板的好教程:https://codereview.stackexchange.com/questions/164650/drawing-a-board-for-the-board-game-go-html-canvas

最新更新