gpt4 book ai didi

javascript - React Web 应用程序遇到严重延迟

转载 作者:行者123 更新时间:2023-11-28 04:03:18 27 4
gpt4 key购买 nike

我在 React 中有一个应用程序,它模拟康威的生命游戏。它由一个简单的 2D 数组组成,每 0.01 秒更新一次 setInterval() 函数指定的新元素。然而,在前 5 秒平稳运行后,速度明显减慢,直到每 0.5 秒左右更新一次。当我试图找出导致应用程序速度如此缓慢的原因时,我一直不知所措。

这是渲染 2D 数组的整个网格组件:

var React = require('react');
var createReactClass = require('create-react-class');
var ReactDOM = require('react-dom');
var Button = require('react-bootstrap').Button;
var Row = require('react-bootstrap').Row;
var Col = require('react-bootstrap').Col;
var FontAwesome = require('react-fontawesome');

// components
var Cell = require('./Cell.jsx');

var Grid = createReactClass({
getInitialState: function() {
return {
matrix: [],
generations: 0,
neighborCells: [[0, 1], [1, 0], [-1, 0], [0, -1], [-1, -1], [1, 1], [-1, 1], [1, -1]]
};
},

componentWillMount: function() {
this.freshGrid();
},

freshGrid: function() {
var matrix = [];
var dim = this.props.dim;

var Cell = function() {
this.neighborsCount = 0;
this.isAlive = false;
}

var counter = 0;
for (var i = 0; i < dim; i++) {
var row = [];
for (var j = 0; j < dim; j++) {
counter++;
var cell = new Cell();
row.push(cell);

if (counter%2 == 0) {
cell.isAlive = true;
}
}
matrix.push(row);
}

this.setState({matrix: matrix}, function() {
this.createGrid();
});
},

createGrid: function() {
this.interval = setInterval(function() {
this.countNeighbours();
this.updateCells();
this.forceUpdate();
this.clearNeighborsCount();
}.bind(this), 10);
},

countNeighbours: function() {
var dim = this.props.dim;

for (var i = 0; i < dim; i++) {
for (var j = 0; j < dim; j++) {
this.countNeighboursCell(i, j);
}
}
},

countNeighboursCell: function(row, col) {
var neighborCells = this.state.neighborCells;
var cell = this.state.matrix[row][col];

for (var i = 0; i < neighborCells.length; i++) {
var neighborPos = neighborCells[i];
var x = row + neighborPos[0];
var y = col + neighborPos[1];

if (this.isWithinGrid(x, y)) {
var neighbor = this.state.matrix[x][y];
if (neighbor.isAlive) {
cell.neighborsCount++;
}
}
}
},

isWithinGrid: function(row, col) {
var dim = this.props.dim;

if (row >= 0 && col >= 0 && row < dim && col < dim) {
return true;
}
return false;
},

updateCells: function() {
var dim = this.props.dim;

for (var i = 0; i < dim; i++) {
for (var j = 0; j < dim; j++) {
var currentCell = this.state.matrix[i][j];

if (currentCell.isAlive && (currentCell.neighborsCount == 2 || currentCell.neighborsCount == 3)) {
currentCell.isAlive = true;
} else if (!currentCell.isAlive && currentCell.neighborsCount == 3) {
currentCell.isAlive = true;
} else {
currentCell.isAlive = false;
}
}
}
},

clearNeighborsCount: function() {
var dim = this.props.dim;

for (var i = 0; i < dim; i++) {
for (var j = 0; j < dim; j++) {
this.state.matrix[i][j].neighborsCount = 0;
}
}
},

togglePause: function(e) {
if (e.target.innerHTML === 'Pause') {
clearInterval(this.interval);
e.target.innerHTML = 'Play';
} else {
e.target.innerHTML = 'Pause';
this.createGrid();
}
},

reset: function() {
this.freshGrid();
},

render: function() {
var dim = this.props.dim;

var cells = [];
for (var i = 0; i < dim; i++) {
var row = [];
for (var j = 0; j < dim; j++) {
row.push(<Cell key={i+j} row={i} col={j} dim={10} isAlive={this.state.matrix[i][j].isAlive} />)
}
cells.push(row);
};

var gridStyle = {
width: this.props.dim * 10,
height: this.props.dim * 10,
background: "#FAFAFA",
margin: "0 auto",
WebKitBoxShadow: "0 0 5px rgba(0, 0, 0, 1)",
MozBoxShadow: "0 0 5px rgba(0, 0, 0, 1)",
boxShadow: "0 0 5px rgba(0, 0, 0, 1)"
};

return (
<Row>
<Col xs={12} md={2}>
<Button onClick={this.togglePause} bsStyle="warning">Pause</Button>
{/* <Button onClick={this.reset} bsStyle="danger">Reset</Button> */}
</Col>

<Col xs={12} md={10}>
<div style={gridStyle}>
{cells}
</div>
</Col>
</Row>
);
}
});

module.exports = Grid;

正如您在 createGrid() 函数中所看到的,我们每 0.01 秒就用新元素更新一次网格。然而,随着时间的推移,速度会大大减慢。我正在尝试找出导致其严重滞后的原因。它发生在所有浏览器以及移动设备上。

编辑:

根据要求,这里是 Cell.jsx

var React = require('react');
var createReactClass = require('create-react-class');

var Cell = createReactClass({

render: function() {
var dim = this.props.dim;

var cellStyle = {
width: dim,
height: dim,
dislay: "inline-block",
float: "left",
border: "1px solid #000",
background: this.props.isAlive ? "#FFF" : "#151515"
};

return(
<div className="cell" onClick={this.clicked} style={cellStyle}></div>
);
}
});

module.exports = Cell;

编辑2:

You can render the grid with this App component

var React = require('react');
var createReactClass = require('create-react-class');

// components
var Grid = require('./Grid.jsx');

var App = createReactClass({
render: function(){
return(
<Grid dim={51}/>
);
}
});

module.exports = App;

最佳答案

基于现有代码的一些提示 -

  1. 不要使用计时器。您可以渲染一次矩阵,而不是计时器,然后在 componentDidUpdate 中调用更新矩阵的函数。在此函数中,您将使用 setState 将新矩阵存储回状态,这将触发新状态的 render。这将永远持续下去,但不会堆积多次执行。

  2. 使用不可变状态。当前代码直接引用state.matrix并更新cells。这将改变状态而不重新渲染。您可以使用 Object.assign 来实现此目的,也可以使用 ImmutableJS。

  3. 重构您的代码以按以下方式执行此操作 -

    计算矩阵>渲染>重复

    编写一个函数,例如calculateMatrix,它接受当前矩阵并返回下一个矩阵。编写另一个函数 updateMatrix,它在当前矩阵上调用 calculateMatrix,然后调用 setState 将新矩阵存储到状态中。在 componentDidMountcomponentDidUpdate 中调用 updateMatrix。这将开始计算 > 渲染 > 无限重复循环。

关于javascript - React Web 应用程序遇到严重延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46904826/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com