Clearing state es6 React

前端 未结 13 840
独厮守ぢ
独厮守ぢ 2020-12-07 13:04

I am trying to clear a components state but can\'t find a reference for the es6 syntax. I was using:

this.replaceState(this.getInitialState());

13条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 14:01

    class x extends Components {
    constructor() {
     super();
     this.state = {
    
      name: 'mark',
      age: 32,
      isAdmin: true,
      hits: 0,
    
      // since this.state is an object
      // simply add a method..
    
      resetSelectively() {
             //i don't want to reset both name and age
        // THIS IS FOR TRANSPARENCY. You don't need to code for name and age
        // it will assume the values in default..
        // this.name = this.name;   //which means the current state.
        // this.age = this.age;
    
    
        // do reset isAdmin and hits(suppose this.state.hits is 100 now)
    
        isAdmin = false;
        hits = 0;
      }// resetSelectively..
    
    }//constructor..
    
    /* now from any function i can just call */
    myfunction() {
      /**
       * this function code..
       */
       resetValues();
    
    }// myfunction..
    
    resetValues() {
      this.state.resetSelectively();
    }//resetValues
    
    /////
    //finally you can reset the values in constructor selectively at any point
    
    ...rest of the class..
    
    }//class
    

提交回复
热议问题