Reputation: 139
import React, {Component} from 'react';
import Square from './components/board.js';
const spaceArr = ()=> {
const arr =[];
for (var i=0; i<20; i++){
arr.push(Math.floor(Math.random()*(400-0)));
}
return arr;
};
class App extends Component{
constructor(){
super();
this.state={
spaces: spaceArr(),
array : new Array(400).fill(false)
} ;
var th = this;
this.state.spaces.map(function(value){
th.state.array.splice(value, 1, true)});
this.click= this.click.bind(this);
}
componentDidMount(){
this.setState({array: this.state.array})
}
click(i, live) {
this.state.array[i]= !live;
var array = this.state.array;
this.setState({array: array}, function(){
console.log(array[i])
})
}
render(){
var th = this;
return (
<div>
<div className='backboard'>
<div className='board'>
{this.state.array.map(function(live, index){
return <Square key={index} living={live} clicker=
{th.click.bind(this, index, live)}/>
})
}
</div>
</div>
</div>
)
}
}
export default App;
I am trying to figure out how to re-render the updated state change after setState. the click event is a handler that is passed to a child component. the updated array should re-render an updated rendering of child components.
Upvotes: 0
Views: 117
Reputation: 139
thanks everyone for trying to answer. My mistake was in setting the "live" attribute in the child component as a state. I instead just passed it as a props directly to the render method conditionals, and that has resolved the issue entirely. also, I think in solving asynch setState method, a good bypass is changing state by setting it to a callback within the property eg.(setState({prop: someFunction()})). Anyway, thanks again.
Upvotes: 1
Reputation: 1593
on your return it should be,
return (<Square key={index} living={live}
clicker= {th.click.bind(th, index, live)}/>
});
Upvotes: 1
Reputation: 13916
You shouldn't mutate this.state directly as mentioned in React docs. Use concat for getting a new array before setting the new state:
click(i, live) {
var newArray = this.state.array.concat();
newArray[i]!=live
this.setState({array: newArray}, function(){
console.log(this.state.array[i]);
})
}
Upvotes: 1
Reputation: 2257
Try this.
click(i, live) {
var array = this.state.array;
array[i]=!live
this.setState({array:array}, function(){
console.log(this.state.array[i])
})
}
Upvotes: 1