我用的是反应。这是我的状态
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 || ''发布于 2020-03-19 19:15:29
您可以设置像initialState这样的变量。
const initialState = {
customerData: {
id: '',
name: '',
type: '',
place: '',
country: '',
timezone: 'GMT+5:30',
status: false
}
}在隐藏模式之前,请执行以下操作:
this.setState(initialState)发布于 2020-03-19 19:13:53
假设您希望保留customerData键,对于用例来说,将所有内容设置为null就足够了,这将简化重置:
this.setState(customerData: Object.assign(...Object.keys(this.state.customerData).map(k => ({[k]: null}))))
https://jsfiddle.net/0ymx7fsq/
或者,由于您使用的是类组件,您还可以将初始状态保存在构造函数中:
constructor(props) {
super(props)
this.state = initialState;
}
...
reset() {
this.setState({ customerData : initialState.customerData });
}
...https://stackoverflow.com/questions/60763441
复制相似问题