在编写康威的生命游戏时,我收到一个错误,状态实际上并未更新。我收到一条警告:setState(...): Can only update a Mounted or Mounting component.
,但到目前为止我尝试过的所有方法都没有帮助。您可以在下面找到我的应用程序组件:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
board: [],
rows: 50,
cols: 50,
cycles: 0
}
this.createBoard();
}
createBoard() {
var newBoard = [];
for (var i = 0; i < this.state.rows; i++) {
var row = [];
for (var j = 0; j < this.state.cols; j++) {
let fillValue;
if (Math.random() > 0.65) {
fillValue = true;
} else {
fillValue = false;
}
row.push(fillValue);
}
newBoard.push(row);
}
console.log(newBoard);
this.setState({board: newBoard});
}
render() {
return(
<div id="root">
<h1>Conway's Game of Life</h1>
<Controller />
{console.log(this.state.board)}
<Board
board={this.state.board}
rows={this.state.rows}
cols={this.state.cols}
/>
<p>Years Passed: {this.state.cycles}</p>
</div>
);
}
}
问题出在 createBoard()
函数末尾的 setState。 setState 上面的 console.log
打印效果很好,但 render 方法中的另一个打印出一个空数组。
最佳答案
更改调用 createBoard() 方法的位置可以修复此错误。我没有调用方法是构造函数,而是将其移至 componentDidMount 请注意,您的两个组件 Board 和 Controller 代码中缺失,因此我已将其注释掉
这是代码
class TestJS extends React.Component {
constructor(props) {
super(props);
this.state = {
board: [],
rows: 50,
cols: 50,
cycles: 0
};
this.createBoard = this.createBoard.bind(this);
}
componentDidMount(){
this.createBoard();
}
createBoard() {
var newBoard = [];
for (var i = 0; i < this.state.rows; i++) {
var row = [];
for (var j = 0; j < this.state.cols; j++) {
let fillValue;
if (Math.random() > 0.65) {
fillValue = true;
} else {
fillValue = false;
}
row.push(fillValue);
}
newBoard.push(row);
}
console.log(newBoard);
this.setState({board: newBoard});
}
render() {
return(
<div id="root">
<h1>Conway's Game of Life</h1>
{console.log(this.state.board)}
<p>Years Passed: {this.state.cycles}</p>
</div>
);
}
}
export default TestJS;
关于javascript - setState 更新挂载状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49143859/