如何将单个状态属性重置为其初始值



我有一个包含以下构造函数的 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})

最新更新