【问题标题】:date-fns and react - while loop adds 1 more day after checking given if statement conditiondate-fns 和 react - while 循环在检查给定的 if 语句条件后又增加了 1 天
【发布时间】:2020-08-14 14:17:59
【问题描述】:

我使用 date-fns 创建了一个带有 React 钩子的日历, 关注这篇文章 -> https://medium.com/@w.difulvio523/create-a-custom-hooks-calendar-in-react-e50bbba456e1

并添加了显示我从后端获取的schedules 的功能。

逻辑是,如果schedule对象date与cloneDay相同, 渲染额外的Link 元素,用户可以单击该元素并转到匹配的schedule 页面。

问题是schedule 是在实际计划日+ 1 渲染的。

例如。如果日期是 14 号,它将在 15 号渲染

这个问题发生在 cell 函数内部

    const cells = () => {
        const monthStart = startOfMonth(currentDate) 
        const monthEnd = endOfMonth(monthStart) 
        const startDate = startOfWeek(monthStart, {weekStartsOn: 1}) 
        const endDate = endOfWeek(monthEnd)
        const dateFormat = "d" 
        const rows = []
        let days = []
        let day = startDate 
        let formattedDate = ""

        //here get the schdules
        //and render in cells.
        //if the schduels.date is same as 'day' or 'clone day', 
        //render <Link/> to Exercise element with corresponding ID

        while (day <= endDate) {
            for (let i = 0; i < 7; i++) {
                formattedDate = format(day, dateFormat) 
                const cloneDay = day
            
                //split and reforamt the cloneDay to compare with schedule object's date
                const formatCloneDay = cloneDay.toISOString().split('T')[0]
                // console.log('formatCloneDay', formatCloneDay)

                const scheduleElements = exerciseScheduleArray.map(schedule => {
                    //reformat for the compare with formatCloneday
                    const formatScheduleDate = schedule.date.split('T')[0]

                    const hasMatchingDays = formatScheduleDate.toString() === formatCloneDay.toString()

                    if(hasMatchingDays) {
                        //here it adds 1 day from matching day
                        return (
                            <Link className="schedule-link" to="/exercise/:exerciseId" key={schedule._id}>
                                <span>{schedule.bodySection} {schedule.duration}</span> 
                            </Link>
                        )
                    }
                    else return null
                })

                days.push( 
                    <div
                        className={`column cell ${
                            !isSameMonth(day, monthStart) ? "disabled" : 
                            isSameDay(day, selectedDate) ? "selected" : "" }`}
                        key={day}
                        onClick={() => onClickDate(cloneDay)} 
                    >
                        <span className="number">{formattedDate}</span>
                        <span className="bg">{formattedDate}</span> 
                        {hasSchedules ? scheduleElements : null}
                    </div>
                )
                //this will increase the day value by 1 each time it iterates
                day = addDays(day, 1)
            }
            rows.push(
                <div className="row" key={day}> {days} </div>
            )
            //if 7 days has been pushed to the rows, delete the days
            //so it could start a new row with new days
            days = []
        }
        return <div className="body">{rows}</div> 
    }

我追踪了 'cloneDay' 值,这个 +1 行为发生在 if 语句中 它检查hasMatchingDays。特别是在.map函数中。

                const scheduleElements = exerciseScheduleArray.map(schedule => {
                    //reformat for the compare with formatCloneday
                    const formatScheduleDate = schedule.date.split('T')[0]

                    const hasMatchingDays = formatScheduleDate.toString() === formatCloneDay.toString()

                    if(hasMatchingDays) {
                        //here it adds 1 day from matching day
                        return (
                            <Link className="schedule-link" to="/exercise/:exerciseId" key={schedule._id}>
                                <span>{schedule.bodySection} {schedule.duration}</span> 
                            </Link>
                        )
                    }
                    else return null
                })

我想知道为什么会导致 +1 天,我如何才能在正确的日期呈现日程安排?

_

exerciseScheduleArray 看起来像这样

【问题讨论】:

  • 乍一看,您的日程安排可能会使用基于 1 的计数,而您的周计数可能使用基于 0 的计数。因此,您的工作日是 0、1、2、3、4、5、6 - 但您的日程安排天数是 1、2、3 ......这里的代码有点难以理解,但这些“关闭一个”错误通常是由索引从 0 或 1 开始而应该是另一个引起的,或者它们是由循环检查 &lt;= 而不仅仅是 &lt; 引起的(反之亦然)。
  • 你能提供一个你的 exerciseScheduleArray 对象的例子吗?
  • @BrettEast 啊,是的,我希望日历从星期一而不是星期日开始,所以我使用了 let startDate = startOfWeek(currentDate, {weekStartsOn: 1}),我将 weekStartsOn 的值更改为 1。所以这可能是有问题吗?
  • @LuisPauloPinto 确定!我将编辑并添加问题
  • 嗨@yoonvak,我复制了文章代码,然后我粘贴了你的单元格函数,创建了一个练习ScheduleArray 模拟,看起来对我来说一切正常,在正确的日期内显示时间表链接。我所做的唯一一件事就是将 hasSchedules 设置为始终为真,因为我现在不知道如何获得此值。所以我相信我们在这里遗漏了一些东西。

标签: javascript reactjs date date-fns


【解决方案1】:

经过长时间的搜索, 我发现了有关 date-fns UTC 时区的问题。

正如这个帖子中提到的, https://github.com/date-fns/date-fns/issues/376

这可能是cell 函数在美国以正确日期或相同时区呈现时间表的原因,

并且会在 t.ex Berlin 渲染 day + 1。

现在,我将切换到 moment.js 以重新创建 cell 函数作为解决方案。 希望这对遇到和我一样问题的人有所帮助。

【讨论】:

  • 注意! moment.js 仍然是同样的问题,所以我真的找不到问题所在?
猜你喜欢
  • 1970-01-01
  • 2021-08-14
  • 2013-06-09
  • 2016-01-12
  • 2012-06-18
  • 2015-05-19
  • 2019-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多