react-hooks - 将钩子数组反应为要在反应本机日历中使用的特定格式
问题描述
对于每个循环,我都有这种格式的日期值。每个循环提供以下格式的值。
开始: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'}],
}}
解决方案
将您的 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
}, {})
推荐阅读
- paho - pythonanywher 上的 paho-mqtt 身份验证错误
- r - rbind 具有不同名称的数据帧
- c# - 带有复选框布尔值和分页的 ViewModel
- reactjs - 在 clojurescript 中,如何评估列表
- python - 一个 POST 请求被判断为 NOT POST 方法
- ckeditor5 - CKEditor5:防止在输入时将属性复制到新段落
- c# - 需要帮助在 c# 中将数据写入 json
- android - Try Everywhere 但没有得到关于 RecyclerView 中 SearchView 的满意答案
- python - 尝试使用单独的 py 文件在 Maya 中动态填充窗口以构建模块
- python-3.x - 错误线seaborn factorplot没有出现