You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中调用Google日历API后如何批量生成自定义对象数组?

问题原因分析
  • 变量定义错误:你声明的google是单个普通变量,而非数组类型,每次赋值都会覆盖上一次的结果,最终只会保留最后一次遍历生成的对象
  • 遍历逻辑冗余:你同时使用了for循环和map遍历,相当于对data数组做了N*N次无意义的重复遍历
  • 未正确收集遍历结果:map方法本身会返回一个新数组,你没有接收这个返回值,也没有在遍历过程中往数组里存入生成的对象
修正后代码
// 初始化为数组类型
let google = [];

useEffect(() => {
    axios.get('https://www.googleapis.com/calendar/v3/calendars/en.australian%23holiday%40group.v.calendar.google.com/events?key=personalkey')
        .then(res => {
            const data = res.data.items;
            console.log("Google api calendar data", data)
            // 直接用map遍历生成新数组,无需额外for循环
            google = data.map((item) => {
                return {
                    "id": item.id,
                    "title": item.summary,
                    "location": "Australia",
                    "start": new Date(moment(item.start.date)),
                    "end": new Date(moment(item.end.date)),
                    "description": item.description,
                    "durationday": 'Fullday',
                    "sameId": null
                }
            })
            console.log("goggle making array of object inside promise", google)
        })
        .catch(err => { console.log('Google api calendar error', err) })
}, [])
优化提示
  • 如果你使用的是React框架,google变量建议用useState声明为状态变量,这样数据更新后可以触发视图重新渲染,直接展示在你的日历组件中
  • 如果你不需要兼容旧版本浏览器,可以把moment替换为原生的日期处理方法,减少依赖包体积

内容的提问来源于stack exchange,提问作者Sharanjeet Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 14:45:03