'setState not running in nested function
this.setState at the end of constructBoard doesn't appear to run when contructBoard is called. The function runs and works as intended other that setState not appearing to run. The callback function doesn't run either.
class Board extends Component {
state = {
layout: null
}
contructBoard = (boardSize) => {
let board = []
let boardStateLayout = {}
for (let row = 0; row < boardSize; row++) {
let temp = []
for (let column = 0; column < boardSize; column++) {
let style = null;
let key = row.toString() + column.toString()
//Top left corner
if (row === 0 && column === 0) {
style = "topLeft"
//Top right corner
} else if (row === 0 && column === boardSize - 1) {
style = "topRight"
//Bottom left corner
} else if (row === boardSize - 1 && column === 0) {
style = "bottomLeft"
//Bottom right corner
} else if (row === boardSize - 1 && column === boardSize - 1) {
style = "bottomRight"
//Top row
} else if (row === 0 && (column > 0 && column < boardSize - 1)) {
style = "topRow"
//First column
} else if (column === 0 && (row > 0 && row < boardSize - 1)) {
style = "firstColumn"
//Bottom Row
} else if (row === boardSize - 1 && (column > 0 && column < boardSize - 1)) {
style = "bottomRow"
//Last column
} else if (column === boardSize - 1 && (row > 0 && row < boardSize - 1)) {
style = "lastColumn"
} else {
style = "middle"
}
temp.push(<td key={key} onClick={this.handleSquareClick} className={style}></td>);
boardStateLayout[key] = {
showEl: false,
el: "x"
}
}
board.push(<tr key={"row" + row.toString()}>{temp}</tr>)
}
this.setState({layout: boardStateLayout}, () => console.log('set state'));
return <table className="board"><tbody>{board}</tbody></table>
}
board = this.contructBoard(3);
render() {
return (
<div className="boardContainer">
{this.board}
{/*<XorO layout={this.state.layout} />*/}
</div>
);
}
}
Solution 1:[1]
You're basically trying to call setState during the component's construction which React Docs discourage.
If you want to set an initial state like that you should add a constructor and assign the state directly.
Like this:
this.state = { layout: boardStateLayout }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barry Michael Doyle |
