javascript - React - 使用 .map 函数和新的 Array.fill 更新二维数组的状态并用随机数填充
问题描述
我正在开发 John Conway 的 Game of Life 应用程序,并且仍在学习 React。
这是我到目前为止所拥有的。游戏板是在我App.js
的状态下使用二维数组创建的。我在构造函数中使用 new Array 和 .fill 方法来最初创建棋盘的方格。稍后,App.js
我有一个名为 isSquareAlive 的函数,它处理 onClick 功能并在用户单击它们时将相应的方块更改为不同的颜色(它们在生命游戏意义上是“活着的”)。
我现在要做的是在用户首次加载应用程序时生成一个随机板,其中一些方块将处于活动状态,而另一些则不会。我创建了一个随机数函数,称为getRandomNumber
创建 1 或 0。现在我想创建另一个将在 componentDidMount 上调用的函数,当用户加载应用程序时,该函数将创建一个初始游戏板,它会调用getRandomNumber
并填充一些二维数组的元素(正方形)中的元素为 1,其他元素为 0。带有 1 的正方形将是“活的”,而带有 0 的正方形则不会。
换句话说,每次用户加载页面时,我都想要一个随机生成的游戏板。我该怎么做?嵌套 .map 函数,然后将结果推getRandomNumber
送到新的 Array.fill 中?
这是我的App.js
:
import React, { Component } from 'react';
import './App.css';
import GameBoard from './GameBoard.js';
import Controls from './Controls.js';
import update from 'immutability-helper';
import Info from './Info.js';
class App extends Component {
constructor(props){
super(props);
this.state = {
boardHeight: 50,
boardWidth: 30,
iterations: 10,
reset: false,
alive: false,
board: [],
randomNum: ''
};
this.state.board = new Array(this.state.boardHeight).fill(new Array(this.state.boardWidth).fill(0));
}
// Allows user to click button and change size of game board
selectBoardSize = (width, height) => {
this.setState({
boardHeight: height,
boardWidth: width,
board: new Array(this.state.boardHeight).fill(new Array(this.state.boardWidth).fill(0))
});
}
// Resets game board back to blank when user clicks reset button
onReset = () => {
this.setState({ board: new Array(this.state.boardHeight).fill(new Array(this.state.boardWidth).fill(0)) })
}
// Generates random number
getRandomNumber = (max) => {
return Math.floor(Math.random() * Math.floor(max));
}
/* This is the function I am trying to build and generate a random starting game board with
componentDidMount = () => {
// Stores random number 1 or 2
const number = this.getRandomNumber(2);
const data = this.state.board;
// This is what I need help on
const startingBoard = data.map((row, y) => {
row.map((ea, x) => {
return 1;
})
})
// After startingBoard is working I can set state with startingBoard
this.setState({
board: startingBoard
});
}
*/
// Called when user clicks on specific square. Changes color of square depending on if it's alive or not
isSquareAlive = (x, y) => {
const data = this.state.board;
const ySquare = y;
const xSquare = x;
const newData = data.map((row, y) => {
return y === ySquare ? (
row.map((cell, x) => x === xSquare ? (cell + 1) % 2 : cell)
) : (
row
)
})
this.setState({ board: newData });
}
render() {
/*console.log('Random number is : ' + this.state.randomNum);*/
return (
<div>
<div className="game-container">
<GameBoard
height={this.state.boardHeight}
width={this.state.boardWidth}
reset={this.onReset}
board={this.state.board}
alive={this.isSquareAlive}
isAlive={this.state.alive}
/>
<Controls
selectBoardSize={this.selectBoardSize}
iterations={this.state.iterations}
onReset={this.onReset}
/>
</div>
<div className="info-container">
<Info />
</div>
</div>
);
}
}
export default App;
return 1 instartingBoard
只是我是一个菜鸟,并试图让它返回一些东西。
重申一下:董事会是这样创建的:
this.state.board = new Array(this.state.boardHeight).fill(new Array(this.state.boardWidth).fill(0));
如何将随机数推入二维数组?
解决方案
这是一个简化的应用程序。我认为在构造函数中设置 state.board 的初始值可能会起作用。这应该会在用户每次启动应用程序时有效地创建一个新板。
import React, {Component} from 'react';
const createRandomBoard = (height, width) => {
const randomCellValue = () => (Math.random() < 0.5 ? 1 : 0);
// thank you @simonbor on StackOverflow:
// https://stackoverflow.com/questions/5836833/create-a-array-with-random-values-in-javascript
const createRow = () => Array.from({length: width}, randomCellValue);
return Array.from({length: height}, createRow);
};
class App extends Component {
constructor(props){
super(props);
const boardHeight = 50;
const boardWidth = 30;
this.state = {
boardHeight,
boardWidth,
board: createRandomBoard(boardHeight, boardWidth),
};
}
render() {
return (
<div>
</div>
);
}
}
export default App;
坐在 stackblitz 上:https ://stackblitz.com/edit/so-gol-answer?file=App.js
推荐阅读
- typescript - Ionic4 的键盘问题
- spring-boot - 使用 feign 和 kubernetes 进行负载平衡
- amazon-web-services - Lambda arn:aws:lambda:us-east-1:xxxxxxxxx:function:nodejs-alexa-skill 的触发器设置无效。错误代码:SkillManifestError
- android - 如何自动接受android权限
- r - dplyr - 如何过滤具有更多(总和)销售额的前 n 个组?
- html - 占位符“搜索表单”从我的计算机上的 c: 位置运行 html 时显示,但在服务器上没有 html 的副本
- reactjs - 使用 .reduce 包装 React 导出
- php - laravel - 制作一个搜索表单并在同一页面中显示结果
- python - 使用 node2vec 创建嵌入
- python - 将json列表转换为字符串