I Have this code in React Native
class Home extends Component {
constructor(props) {
super(props);
this.initialState={
backGroundColor: '#ffffff',
visible:[true,true,true,true,true,true],
progress:0,
numbers: shuffle([1,2,3,4,5,6])
}
this.state = this.initialState;
}
_resetState(){
this.setState(this.initialState);
}
_change(teste,op){
if(op==this.state.numbers[0]){
let array = this.state.visible;
switch(op){
case 1:
array[op-1] = false;
break;
case 2:
array[op-1] = false;
break;
case 3:
array[op-1] = false;
break;
case 4:
array[op-1] = false;
break;
case 5:
array[op-1] = false;
break;
case 6:
array[op-1] = false;
break;
}
this.setState({backGroundColor: teste,visible:array,progress: this.state.progress+0.16666666666666});
this.state.numbers.splice(0,1);
}else{
console.log(this.initialState);
}
}
When I do console.log(this.initialState) the arrays numbers and visible inside the state is not the initial but the backGroundColor and progress are the initial values. Why this happened? How can i keep their initial values ? I need back to initial state all elements (including the two arrays) .
In your constructor, you could assign a copy of your initialState instead of the original object, ie.:
this.state = Object.assign({}, this.initialState);
I don't know React well enough to know if this is the best pattern for re-initialising state, but it should work.
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.