[英]How to manage nested object with React Native State
I am trying to build a water reminder app. 我正在尝试构建水提醒应用程序。 I have 4 screens and I am using react-navigation
我有4个屏幕,我正在使用反应导航
I have state in my apps such as drunk, goal etc. Everyday I am setting drunk value to zero that users can start over again. 我的应用程式中有状态,例如醉酒,目标等。每天,我会将醉酒值设为零,以便使用者可以重新开始。
What I have done is that I have created new state called object and set it to empty object. 我所做的是创建了一个名为object的新状态并将其设置为空对象。 And I was able to update history state as below with state handler function.
而且我能够使用状态处理程序功能按如下方式更新历史记录状态。
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,
}
What i need is that nested object with dates with keys as date 我需要的是带有键作为日期的日期的嵌套对象
history: {
"20052019": {
"date": "20052019",
"drunk": 136,
"goal": 82,
"progress": 1.6585365853658536,
},
"21052019": {
"date": "21052019",
"drunk": 82,
"goal": 82,
"progress": 1.0,
}
}
You can dynamically access/create keys using object[key]
. 您可以使用
object[key]
动态访问/创建密钥。
handleHistory = () => {
const currentDateString = moment().format('DDMMYYYY');
const { history, drunk, goal, progress } = this.state;
this.setState({
history: {
...history,
[currentDateString]: {
...history[currentDateString],
date: currentDateString,
drunk, goal, progress
}
}
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.