state가 바뀔때마다 갤러리 컴포넌트를 새로 재 렌더링하고 싶었는데, useEffect에 clean up 함수를 쓰는 바람에 갤러리컴포넌트가 한번만 실행이 되었다. 그래서 pictures가 바뀌는 코드를 짜도 바뀌지 않았던 것이다.
import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from "react-redux";
import { Motion, spring } from 'react-motion';
import styled from 'styled-components';
import picturesUrl from '../../dummyData/dummyPictures';
import Menubar from './Menubar';
import MenuView from './MenuView';
import ViewDetail from './ViewDetail';
function Gallery({ }) {
const [forCleanUp, setForCleanUp] = useState(true);
const [pictures, setPictures] = useState([]);
const [isPictureSelected, setIsPictureSelected] = useState(false);
const [testConut, setTestCount] = useState(0);
const dispatch = useDispatch();
const category = useSelector(state => {
return state.reducerMenu.category
});
useEffect(() => {
if (forCleanUp) {
console.log('category : ', category);
console.log("picturesUrl[category] : ", picturesUrl[category]);
setPictures(picturesUrl[category]);
let temp = testConut + 1;
setTestCount(temp);
console.log('testConut : ', testConut);
// 웹 서버 구현하면 여기서 Ajax요청할 것
}
return () => {
setForCleanUp(false);
}
}, [forCleanUp]);
return (
<>
{isPictureSelected ? <ViewDetail closeDetail={setIsPictureSelected}/> :
<>
<MenuView />
<Menubar />
<div onClick={() => {
dispatch({ type: 'CLOSE_MENU' })
}}>
<Motion
defaultStyle={{ x: -200, opacity: 0 }}
style={{ x: spring(0), opacity: spring(1) }}
>
{(style) => (
<Div>
{pictures.map((el, idx) =>
<Img src={el.src}
key={idx}
style={{ opacity: style.opacity }}
onClick={() => {
dispatch({
type: 'CHANGE_VIEWDETAIL',
payload: {
picture: el
}
});
setIsPictureSelected(!isPictureSelected);
}}></Img>
)}
</Div>
)}
</Motion>
</div>
</>
}
</>
)
}
const Div = styled.div`
text-align: center;
`;
const Img = styled.img`
/* padding: 25px; */
width: 70%;
height: 30%;
animation-name: name;
animation-duration: 5s;
`;
export default Gallery
참고자료 ⇒ https://react.vlpt.us/basic/16-useEffect.html
React Hook useEffect contains a call to 'setPictures'. Without a list of dependencies, this can lead to an infinite chain of updates. To fix this, pass [category] as a second argument to the useEffect Hook
React Hook useEffect는 'setPictures'에 대한 호출을 포함합니다. 종속성 목록이 없으면 무한한 업데이트 체인이 발생할 수 있습니다. 이 문제를 해결하려면 useEffect Hook의 두 번째 인수로 [category]를 전달하세요.
Unexpected empty object pattern no-empty-pattern
예기치 않은 빈 개체 패턴 no-empty-pattern