简体   繁体   English

如何使用React Native State管理嵌套对象

[英]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个屏幕,我正在使用反应导航

  • Home (that I allow users to increase their amount drink that day and display how much water they drunk) 家庭(我允许用户当天增加饮酒量并显示他们喝了多少水)
  • History (where user's water drinking history is displayed with graph and this is where I need nested object ) 历史记录(用户的饮水历史记录以图形显示,这是我需要嵌套对象的位置)
  • Notifications (where users defining with switch buttons if they want to receive notifications and when to receive) 通知(用户使用开关按钮定义是否要接收通知以及何时接收)
  • Settings (where the user enters age, weight to determine how much they should drink daily). 设置(用户输入年龄,体重来确定每天应该喝多少酒)。 this is the first screen users see when they downloaded the app 这是用户下载应用程序时看到的第一个屏幕

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM