gpt4 book ai didi

javascript - 如何将单个状态 Prop 重置为其初始值

转载 作者:行者123 更新时间:2023-11-30 09:33:12 26 4
gpt4 key购买 nike

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

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

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

有没有办法在不重置其余 Prop 的情况下做到这一点?意思是,不使用:

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

关于javascript - 如何将单个状态 Prop 重置为其初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45065495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com