【问题标题】:How back state to default in React Native?如何在 React Native 中恢复默认状态?
【发布时间】:2017-08-04 07:35:22
【问题描述】:

我在 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 和 progress 是初始值。为什么会这样?我怎样才能保持他们的初始值?我需要将所有元素(包括两个数组)恢复到初始状态。

【问题讨论】:

    标签: javascript react-native frontend


    【解决方案1】:

    在您的构造函数中,您可以分配一个 copy 您的 initialState 而不是原始对象,即:

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

    我不太了解 React,不知道这是否是重新初始化状态的最佳模式,但它应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      相关资源
      最近更新 更多