我的日历可以成功渲染最初的月份,但是单击下一个或上一个月份后,它将不渲染新的月份或之后的任何月份。我的猜测是它要么是渲染问题,要么是我不知道moment.js是否存在某些问题。我尝试使用不同的方式让 CalendarComponents 知道 CurrentMonth 发生了变化(因此需要重新渲染),最近的尝试是 memoizedValue 。
在我看来,要么是渲染问题,要么是我暂时没有看到的moment.js问题。任何帮助将不胜感激。
这是我的代码:
import React, { useState, useEffect, useRef, useMemo } from 'react';
import '../App.css';
import moment from 'moment';
const App = () => {
const [state, setState] = useState({
currentMonth: moment().format('YYYY-MM-DD'),
currentWeek: moment().weeks(),
selectedDate: moment().format('YYYY-MM-DD'),
startDate: moment().format('YYYY-MM-DD')
});
const renderHeader = () => {
return (
<div className="header row flex-middle">
<div className="col col-start">
<div className="icon" onClick={prevMonth}>
Previous month
</div>
</div>
<div className="col col-center">
<span>{moment(state.currentMonth).clone().format('MMMM-YYYY')}</span>
</div>
<div className="col col-end" onClick={nextMonth}>
<div className="icon">Next month</div>
</div>
</div>
);
}
const renderWeekDays = () => {
const days = [];
const weekDays = moment.weekdays();
for (let i = 0; i < 7; i++) {
days.push(
<div className="col col-center" key={i}>
{weekDays[i]}
</div>
);
};
return <div className="days row">{days}</div>;
}
const renderCells = () => {
const monthStart = moment(state.currentMonth).clone().startOf('month').format('YYYY-MM-DD');
const monthEnd = moment(monthStart).clone().endOf('month').format('YYYY-MM-DD');
const startDate = moment(monthStart).clone().startOf('week').format('YYYY-MM-DD');
const endDate = moment(monthEnd).clone().endOf('week').format('YYYY-MM-DD');
console.log(endDate);
const rows = [];
let days = [];
let day = startDate;
console.log(day);
let formattedDate = "";
while (day <= endDate) {
for (let i = 0; i < 7; i++) {
formattedDate = moment(day).format('DD');
const cloneDay = day;
days.push(
<div
className={`col cell ${
!moment(day).isSame(monthStart, 'month')
? "disabled"
: null
}`}
key={day}
>
<span className="number">{formattedDate}</span>
</div>
);
day = moment(day).add(1, 'days').format('YYYY-MM-DD');
}
rows.push(
<div className="row" key={day}>
{days}
</div>
);
days = [];
}
return <div className="body">{rows}</div>;
}
const nextMonth = () => {
setState({
currentMonth: moment(state.currentMonth).add(1, 'month').format('YYYY-MM-DD')
});
};
const prevMonth = () => {
setState({
currentMonth: moment(state.currentMonth).subtract(1, 'month').format('YYYY-MM-DD')
});
};
const CalendarComponents = ({ date }) => {
const monthCalendar = () => {
return (
<div className="calendar" style={{ height: '1000px' }}>
{renderHeader()}
{renderWeekDays()}
{renderCells()}
</div>
)
};
const memoizedValue = useMemo(() => monthCalendar(), [state.currentMonth]);
return memoizedValue;
}
const handleDate = (e) => {
console.log(e);
}
return (
<div className="calendar" style={{ height: '1000px' }}>
<CalendarComponents />
</div>
)
}
export default App;
谢谢。