【发布时间】:2018-09-06 16:26:09
【问题描述】:
尝试在此组件的状态下将对象添加到数组中,无法将新对象连接到数组而没有“属性未定义”错误。
我已经能够让它在带有数组的“浅”状态下工作,但我希望它能够在内部单独的数组中工作。
国家
constructor(props) {
super(props);
this.state = {
show: false,
id: null,
name: 'New Task',
timerOn: false,
seconds: 0,
minutes:0,
hours:0,
complete: {
todayId: null,
list: []
}
}
}
更新状态的方法,制作“控件”(分钟、秒、开始等)的副本,将状态重置为初始值,获取状态副本并将其应用于数组:
completeTaskHandler = () => {
if (this.state.seconds === 0 && this.state.minutes === 0 && this.state.hours === 0) {
alert('Please Provide a name');
}
else {
const end = new Date();
let finishedTask = new Object ({
start: this.state.id,
end: end,
name: this.state.name,
seconds: this.state.seconds,
minutes: this.state.minutes,
hours: this.state.hours,});
this.setState((prevState,props) => {
return {
start: null,
show: false,
id: null,
name: 'task',
timerOn: false,
seconds: 0,
minutes:0,
hours:0,
complete: prevState.complete.list.concat(finishedTask)
}
});
clearInterval(this.interval);
}
}
【问题讨论】:
-
您能否提供更清晰的帮助?
-
尝试记录 'prevState.complete.list' 并查看它是否是您期望的对象(数组)
-
因为列表是一个数组。更改为完成:[...prevState.complete.list, finishedTask]
标签: javascript reactjs react-state-management