I am trying to reset an array using the setState method in React. In the constructor I have set tile_arrays to null initially.
The first console.log() produces the desired array of N Tile objects after the nested for loops finish. When setState is called and the subsuquent console.log() after, the state is still null and was not updated.
I am not trying to append new information to the states array, but replace it entirely.
createTileArray(){
let new_array= [];
let size = this.state.size;
for(let row = 0; row < size; row++){
for(let column = 0; column < size; column++){
if(row === 0 || row === 1){
//Player 1
new_array.push(new Tile(column, row, true, 1))
}
else if(row === size - 1 || row === size - 2){
//Player 2
new_array.push(new Tile(column, row, true, 2))
}
else{
//Empty Tile
new_array.push(new Tile(column, row, false, 0))
}
}
}
console.log("Tile to be set into the state", new_array)
this.setState({
tile_arrays:new_array
},
() => console.log("Updated Tiles: ", this.state.tile_arrays))
}
setState
is asynchronous, but it does allow a callback.
this.setState(
{ tile_arrays: tile_array },
() => console.log("Updated Tiles: ", this.state.tile_arrays)
)
Copied and pasted your code in a snippet to demonstrate the comment I made one hour ago.
Try logging it in render
class Tile { constructor(column, row, something, player) { this.column = column; this.row = row; this.something = something; this.player = player; } } class App extends React.Component { state = { size: 3, }; createTileArray() { let new_array = []; let size = this.state.size; for (let row = 0; row < size; row++) { for (let column = 0; column < size; column++) { if (row === 0 || row === 1) { //Player 1 new_array.push(new Tile(column, row, true, 1)); } else if (row === size - 1 || row === size - 2) { //Player 2 new_array.push(new Tile(column, row, true, 2)); } else { //Empty Tile new_array.push(new Tile(column, row, false, 0)); } } } console.log('Tile to be set into the state', new_array); this.setState({ tile_arrays: new_array, }); } componentDidMount() { this.createTileArray(); } render() { //was that so difficult? console.log('tile arrays', this.state.tile_arrays); return ( <pre>{JSON.stringify(this.state, undefined, 2)}</pre> ); } } ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>
After a little testing, I have found a solution. In my initial constructor for the component, instead of setting
tile_arrays:null
I set it to equal an empty array
tile_arrays:[]
The problem seems to be fixed and working now.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.