简体   繁体   中英

How can I reset a single state prop to its initial values

I have a react component that contains the following constructor:

constructor (props) {
  super(props);
  this.state = {
    stage: TIMER_PREPARED,
    remaining: this.props.seconds,
    flashNotification: {
      message: null,
      shown: false,
      code: null,
    }
  };
}

At a certain point during the app lifecycle I need to reset the flashNotification props to their initial state.

Is there a way to do that without resetting the rest of the props? Meaning, without using:

this.setState({flashNotification: {
      message: null,
      shown: false,
      code: null,
    }})

Just initialize flashNotification using a factory function:

class Comp extends React.Component {
  constructor(props) {
    super(props);   

    this.state = {
      stage: TIMER_PREPARED,
      remaining: this.props.seconds,
      flashNotification: this.createFlashNotification()
    };  
  }

  reset() {
    this.setState({ flashNotification: this.createFlashNotification() });
  }

  createFlashNotification() {
    return {
      message: null,
      shown: false,
      code: null
    }
  }    
}

To reset flashNotification to a base value. You can store the object on this , and clone it whenever you want to reset:

class Comp extends React.Component {
  constructor(props) {
    super(props);

    this.flashNotification = Object.freeze({ // Object.freeze is used to prevent changes to the base object
      message: null,
      shown: false,
      code: null,
    });

    this.state = {
      stage: TIMER_PREPARED,
      remaining: this.props.seconds,
      flashNotification: Object.assign({}, this.flashNotification) // cloning the object
    };

    this.reset = this.reset.bind(this);
  }

  reset() {
    this.setState({ flashNotification: Object.assign({}, this.flashNotification })// cloning the object
  }
}

What I would do is keep a copy of the initial State in a class object and then reset it whenever necessary like

constructor (props) {
  super(props);
  this.baseFlashNotification = {
      message: null,
      shown: false,
      code: null,
    }

  this.state = {
    stage: TIMER_PREPARED,
    remaining: this.props.seconds,
    flashNotification: Object.assign({}, this.baseFlashNotification)
  };
}

and reset as

  this.setState({flashNotification: this.baseFlashNotification})

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM