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.-----Answers------
1. Try this.
2. click(i, live) {
var array = this.state.array;
array[i]=!live
this.setState({array:array}, function(){
console.log(this.state.array[i])
})
}
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]);
})
}
3.
on your return it should be,
return (<Square key={index} living={live}
clicker= {th.click.bind(th, index, live)}/>
});
0 nhận xét:
Post a Comment