목표: 리덕스 상태에서 빈 배열을 반환하고 있을 시에는 input field를 모두 입력하세요. 혹은,
배열이 1 이상일 경우에는 1번째 데이터를 랜더링 하는 페이지를 만들어본다.
과정, 이슈와 해결:
function Todo() {
const recentList = useSelector((state) => state.addTask.todos);
const [emptyList, setEmptyList] = useState(false);
console.log(recentList);
if (recentList.length === 0) {
setEmptyList(true);
}
return (
<>
{emptyList && <p> 위에 폼 작성해</p>}
{!emptyList && (
<div id="myTodaySection">
<ScrollAnimationContainer>
<ToDoLayer>
<TextLayer>
<h2>{recentList?.[0]?.title}</h2>
<hr />
<p>{recentList?.[0]?.date}</p>
<p>{recentList?.[0]?.category}</p>
<p>{recentList?.[0]?.todo}</p>
</TextLayer>
<Img src={recentList?.[0]?.file} alt="img" />
</ToDoLayer>
</ScrollAnimationContainer>
</div>
)}
</>
);
}
export default Todo;
이슈: Too many re-renders ... ! ! !
저번에 리덕스를 만들면서 이 이슈를 맞이했을때는 ()=>{} 버튼을 화살표 함수를 써줘서
무한루프를 막아줬다. 하지만 지금은 버튼을 만들고 있지 않은데 ! !
이걸 해결하기 위해서는 리액트의 리랜더링 세가지 조건을 본다. 2번 인것 같다.
찍어서 useEffect를 써주어보려고 한다.
props 변화
state 변화
부모요소가 리렌더링 될 때
if (recentList.length === 0) {
setEmptyList(true);
}
이 if 문에서 계속 재랜더링이 생기는 것 같다. 추측중 ! ! !
왜냐면 맨처음 페이지를 업로드하면 당연히 아무런 데이터도 없다. 근데 다시 또 저 if문이 실행되고
또 실행되는 듯 ! 저걸 useEffect로 일단 감싸고 의존성에도 recentlist를 추가해줘서 처음랜더링이 실행됐을 때 한번 ! recentlist가 바뀌었을 때 한번 이렇게 두번 검사해줄 것이다.
useEffect(() => {
if (recentList.length === 0) {
setEmptyList(true);
} else if (recentList.length >= 1) {
setEmptyList(false);
}
}, [recentList]);
허어어어얼!! 해결완료 ! !
전체코드:
function Todo() {
const recentList = useSelector((state) => state.addTask.todos);
const [emptyList, setEmptyList] = useState(false);
console.log(recentList);
useEffect(() => {
if (recentList.length === 0) {
setEmptyList(true);
} else if (recentList.length >= 1) {
setEmptyList(false);
}
}, [recentList]);
return (
<>
{emptyList && <p> 위에 폼 작성해</p>}
{!emptyList && (
<div id="myTodaySection">
<ScrollAnimationContainer>
<ToDoLayer>
<TextLayer>
<h2>{recentList?.[0]?.title}</h2>
<hr />
<p>{recentList?.[0]?.date}</p>
<p>{recentList?.[0]?.category}</p>
<p>{recentList?.[0]?.todo}</p>
</TextLayer>
<Img src={recentList?.[0]?.file} alt="img" />
</ToDoLayer>
</ScrollAnimationContainer>
</div>
)}
</>
);
}
export default Todo;