首页 > 解决方案 > 将钩子数组反应为要在反应本机日历中使用的特定格式

问题描述

对于每个循环,我都有这种格式的日期值。每个循环提供以下格式的值。

开始:2021-06-30T18:30:00.000Z 标题:一

开始:2021-07-31T18:30:00.000Z 标题:二

开始:2021-08-31T18:30:00.000Z 标题:三

function loadItems() {
    firebase.database().ref("events").once("value", (userSnapshot) => {
      
      userSnapshot.forEach(element => {
        const start = moment(element.child('start').val()).toDate();
        const title = element.child('title').val();
      )}
   )}
}

我已经创建了这样的变量。

const [items, setItems] = useState([]);
  const [markedDates, setMarkedDates] = useState([]);

我需要将其转换为以下格式。如何使用 useState 更新每个循环的值。

markedDates={{
    '2021-06-30': {selected: true, marked: true},
    '2021-06-30': {selected: true, marked: true},
    '2021-06-30': {selected: true, marked: true},
  }}

items={{
    '2021-06-30': [{name: 'one'}],
    '2021-06-30': [{name: 'two'}],
    '2021-06-30': [{name: 'three'}],
    
  }}

标签: react-hooks

解决方案


将您的 firebase 数组减少到所需的格式。沿着这些路线的东西可以完成这项工作。

const items = userSnapshot.reduce((accumulator: any, item: any) => {
    
  if(accumulator.hasOwnProperty(item.start.slice(0, 10))) {
    accumulator = {...accumulator, [item.start.slice(0, 10)]: [...accumulator[item.start.slice(0, 10)], { name: item.title }]}
  } else {
    accumulator = {...accumulator, [`${item.start.slice(0, 10)}`]: [{ name: item.title }]}
  }

  return accumulator
}, {})

推荐阅读