我正在尝试构建水提醒应用程序。我有4个屏幕,我正在使用反应导航
我的应用程序中有状态,例如醉酒,目标等。每天我将醉酒值设置为零,以便用户可以重新开始。
我所做的是,我创建了一个称为对象的新状态并将其设置为空对象。而且我能够使用状态处理程序功能按如下方式更新历史记录状态。
handleHistory = () => {
let currentDateString = moment().format('DDMMYYYY');
this.setState(
{
history: {
...this.state.history,
date: currentDateString,
drunk: this.state.drunk,
goal: this.state.goal,
progress: this.state.progress,
},
});
};
//this is what I get
Object {
"date": "20052019",
"drunk": 136,
"goal": 82,
"progress": 1.6585365853658536,
}
我需要的是带有日期和键作为日期的嵌套对象
history: {
"20052019": {
"date": "20052019",
"drunk": 136,
"goal": 82,
"progress": 1.6585365853658536,
},
"21052019": {
"date": "21052019",
"drunk": 82,
"goal": 82,
"progress": 1.0,
}
}
答案 0 :(得分:0)
您可以使用object[key]
动态访问/创建密钥。
handleHistory = () => {
const currentDateString = moment().format('DDMMYYYY');
const { history, drunk, goal, progress } = this.state;
history[currentDateString] = {
...history[currentDateString],
date: currentDateString,
drunk, goal, progress
};
this.setState({ history });
};