2017-08-04 185 views
0

我有这样的代码在本地做出反应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); 
    } 
    } 

当我做的console.log(this.initialState)的阵列数量和可见里面的状态不是初始但BACKGROUNDCOLOR和进步是初始值。为什么会发生?我怎样才能保持他们的初始值?我需要回到初始状态的所有元素(包括两个数组)。

回答

0

在你的构造函数,你可以指定你的初始化状态的副本代替了原来的目标,即:

this.state = Object.assign({}, this.initialState); 

我不知道反应良好,足以知道这是不是最好的模式为了重新初始化状态,但它应该工作。