我有一个包含以下构造函数的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,
}})
答案 0 :(得分:2)
使用工厂函数初始化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
}
}
}
答案 1 :(得分:1)
将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
}
}
答案 2 :(得分:1)
我要做的是在类对象中保留初始State的副本,然后在必要时重置它,如
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})