猿问

ReactJS 逻辑中的每日日历

我有一个调用的按钮goNextDay和另一个调用goPreviousDay. 两者都转到正确的月份,但prevMonthDays如果天 === 1,则不会将日期设置为上个月,如果天 === thisMonthDays,则将下个月的日期设置为 1。


这是与下面相同的代码,但有任何即将进行的改进。


转到 src>UIConainers>Calendar>CalSlideDrawer.js


https://codesandbox.io/s/zen-dijkstra-1c31n?fontsize=14


CalSlideDrawer.js 是通过左上角的标志图标找到的(如果您在紫色屏幕上开始,则按下收件箱图标后)


export const getMonthDays = (month, year) => {

  const months30 = [4, 6, 9, 11];

  const leapYear = year % 4 === 0;

  return month === 2

    ? leapYear

      ? 29

      : 28

    : months30.includes(month)

    ? 30

    : 31;

};


export const goPreviousDay = (day, month, year) => {

  const prevMonthDays = getMonthDays(month, year);

  if (day <= 1) {

    const prevMonth = (month > 1) ? month - 1 : 12;

    const prevMonthYear = (month > 1) ? year : year - 1;

    return { month: prevMonth, year: prevMonthYear };

  }

  const prevDay = (day < 2) ? prevMonthDays : day - 1;

  return { day: prevDay, month, year };

};


export const goNextDay = (day, month, year) => {

  const thisMonthDays = getMonthDays(month, year);

  if (day === thisMonthDays) {

    const nextMonth = month < 12 ? month + 1 : 1;

    const nextMonthYear = month < 12 ? year : year + 1;

    return { month: nextMonth, year: nextMonthYear };

  }

  const nextDay = day === thisMonthDays ? 1: day + 1;

  return { day: nextDay, month, year };

};

谢谢阅读。你能说出我的逻辑有什么问题吗?请告知,非常感谢


MYYA
浏览 170回答 1
1回答

万千封印

day如果 day === 1,则不会从该方法返回。因此,day 不会更改。因为你return的 if 语句中有关键字。所以如果 day <= 1,这个代码块将不会因为return关键字而运行。&nbsp; &nbsp; return { month: prevMonth, year: prevMonthYear }; // This breaks the block.}const prevDay = (day < 2) ? prevMonthDays : day - 1; // won't run if day === 1return { day: prevDay, month, year };所以,你可以像这样修复它:export const goPreviousDay = (day, month, year) => {&nbsp; const prevMonthDays = getMonthDays(month, year);&nbsp; let newDay, newMonth, newYear;&nbsp; if (day <= 1) {&nbsp; &nbsp; newDay = prevMonthDays;&nbsp; &nbsp; newMonth = (month > 1) ? month - 1 : 12;&nbsp; &nbsp; newYear = (month > 1) ? year : year - 1;&nbsp; } else {&nbsp; &nbsp; newDay = day - 1;&nbsp; &nbsp; newMonth = month;&nbsp; &nbsp; newYear = year;&nbsp; }&nbsp; return { day: newDay, month: newMonth, year: newYear };};goNextDay 方法也是如此。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答