我想将对象属性值克隆为空变量或空对象。 我不知道我们是否能够实现它,因此我一直在寻找但仍未找到解决方案的疑问
事件具有键-> 名字,姓氏和年龄
我尝试使用设置状态方法直接设置状态
this.setState({currentEvent:event});
这是完整的代码:
this.state = {
dialogEvent:false,
currentEvent:{},
}
}
handleClickButton = event => {
// event is the single event that needs to be updated in parent event
after updating age.
console.log(event);
axios.get(configs.Data.getNewAge)
.then(res=>{
console.log(res); // res.data.newObj has time date and time epoch
Object.keys(event).forEach(function(index){
console.log(index);
}); // checking the keys for event by logging
this.setState({currentEvent:event});
this.setState({eventDialog:true}); // this is the dialog
}).catch((e)=>console.log("Error :"+e));
};
实际结果:如果在对话框中获取,则currentEvent未定义
预期结果:它应该已经克隆了所有属性和值
答案 0 :(得分:2)
使用spread。
const event = {firstName:"fn",lastName:"ln",age:99}
let currentEvent = {...event}
console.log(currentEvent)
答案 1 :(得分:1)
尝试克隆event
对象。
handleClickButton = event => {
const currentEvent = Object.assign({}, event);
axios.get(configs.Data.getNewAge)
.then(res => {
this.setState({currentEvent});
}).catch((e)=>console.log("Error :"+e));
};