繁体   English   中英

如何将单个状态道具重置为其初始值

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

我有一个包含以下构造函数的react组件:

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

在应用程序生命周期的某个时刻,我需要将flashNotification道具重置为其初始状态。

有没有办法在不重置其余道具的情况下做到这一点? 含义,不使用:

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

只需使用工厂函数初始化flashNotification:

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
    }
  }    
}

flashNotification重置为基本值。 您可以将对象存储在this ,并在需要重置时克隆它:

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
  }
}

我要做的是将初始状态的副本保存在类对象中,然后在必要时将其重置,例如

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)
  };
}

并重置为

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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