일단 익숙한 useState으로 먼저 구현해보고, 그 다음 Redux로 바꿔보려고 한다.
month와 year를 변경할 수 있는 버튼을 추가해 놓았다.
그리고 year와 month는 App.tsx에서 useState를 사용하여 버튼을 클릭할 때마다 변경될 수 있도록 해보자. 각 버튼에 onClick 함수를 만들어서 연결해주었다.
그런데 type 오류가 나네...?
function App() {
const date = new Date();
const [year, setYear] = useState(date.getFullYear());
const [month, setMonth] = useState(date.getMonth());
const handleClickPrevYear = () => {
setYear(year - 1);
};
const handleClickNextYear = () => {
setYear(year + 1);
};
const handleClickPrevMonth = () => {
if (month === 0) {
setYear(year - 1);
setMonth(11);
} else setMonth(month - 1);
};
const handleClickNextMonth = () => {
if (month === 11) {
setYear(year + 1);
setMonth(0);
} else setMonth(month + 1);
};
return (
<Table>
<YearWrapper>
<Btn onClick={handleClickPrevYear}>◀️</Btn>
<Year>{year}</Year>
<Btn onClick={handleClickNextYear}>▶️</Btn>
</YearWrapper>
<MonthWrapper>
<Btn onClick={handleClickPrevMonth}>◀️</Btn>
<Month>{month + 1}월</Month>
<Btn onClick={handleClickNextMonth}>▶️</Btn>
</MonthWrapper>
<Days />
<Dates year={year} month={month} /> // 타입 에러~~~!!!! 😈😈😈
</Table>
);
}
export default App;
App.tsx는 아무 잘못 없다. Dates 컴포넌트에서 year와 month props를 받아올 때 type 지정을 잘 해줘야 한다. 나는 interface인 DatesProps를 생성하여 props에 지정해주었다. 물론 이렇게 하니 type 오류는 사라진다.
interface DatesProps {
year: number;
month: number;
}
function Dates({ year, month }: DatesProps) {
const date = new Date();
// const year = date.getFullYear();
// const month = date.getMonth();
.
.
date에서 뽑아냈었던 year와 month는 이제 prop으로 전달 받기 때문에, 위의 코드에서도 마지막 두 줄은 이제 날려버리자. 훨훨~~
다음달을 클릭하면? 두근두근
짜잔!!
useState로 기능 추가 성공!!
useState은 이제 눈 감고 할 때도 됐다. 그치?
다만 이건 다 저번 시간에 month, year 숫자만 바꾸면 날짜가 잘 뜨도록 알고리즘에 신경을 많이 쓴 덕분이다. 만약 저번 시간에 그 과정이 없었다면... 아마 오늘 useState 썼는데 날짜가 이상하게 떠서 또 헤맸겠지? ㅋㅋㅋㅋㅋ 휴 다행!
다음 시간에는 최근에 배운 전역 상태 관리 tool인 redux를 사용해서 바꿔보자.