我用的是反应。这是我的状态
state = {
customerData: {
id: '',
name: '',
type: '',
place: '',
country: '',
timezone: 'GMT+5:30',
status: false
}
}在编辑功能中,customerData对象在单击“编辑”按钮时得到填充。我正在用模态显示这些数据。
现在,在模式中,当我单击submit按钮时,模型应该隐藏,customerData对象中填充的数据应该是空的。我可以这样做:
this.setState({
customerData: {
...this.state.customerData
id: '',
name: '',
type: '',
place: '',
country: '',
timezone: '',
status: false
}
}
})我想知道在ES6中是否有一种使customerData对象为空的行方式。因为,如果有太多的领域,这将是困难的。
发布于 2020-03-19 19:14:33
这里有两个简单的选择:
创建默认对象
在组件之上,您可以为您的状态创建“空”值。例如:
const emptyCustomerData = {
id: '',
name: '',
type: '',
place: '',
country: '',
timezone: '',
status: false,
}当您想清除状态对象时,现在只需调用:
this.setState({
customerData: emptyCustomerData,
})允许customerData的所有值都为空
您可以简单地将customerData设置为空对象:
this.setState({
customerData: {},
})这样做意味着在使用代码中的任何属性之前,需要检查undefined。
// This sets myVal to customerData.name, or if name is undefined, to an empty string
const myVal = this.state.customerData.name || ''https://stackoverflow.com/questions/60763441
复制相似问题