codestates / codestates/art-ground
[Error Handling Log] 서브라우팅 적용하기(갤러리 & 리뷰 상세페이지로 이동할 때) / 박지영
- Dominant language
- JavaScript
- Stars
- 7
- Forks
- 9
- PR merge metrics
- No merged PRs in 30d
Description
### **어떤 에러인가요?**
- 상세페이지에서 새로고침하면 props가 날아가서 exhibition 객체 정보가 랜더링이 안 되는 상황
### **<해결하는 과정>**
- 상세페이지로 이동하였을 때 클라이언트 url의 엔드포인트에 exhibition의 고유 id 값이 들어가게끔 하기
- 그래야지만 상세 페이지에서 새로고침할 때 엔드포인트의 exhibition.id를 활용하여 —> 상세 페이지랜더링에 필요한 정보를 useEffect로 axiosGET요청을 보낼 수 있다.
- 이렇게 되면 서버엔 axios요청을 한 번 더 보내는 대신에, 클라이언트에서 독립적인 페이지 랜더링이 가능하다.
- 아래와 같이 엔드포인트로 exhibition의 id값 넣어 pathname을 변경함.
```jsx
setThreeDSelected(el)}
/>
```
- 상세페이지로 이동하는 이벤트가 일어나는 컴포넌트에서도 이동하는 pathname을 변경시켜준다(기존의 ``태그는 모두 지우고, `history.push`를 사용해줬다.
```jsx
//GalleryContent.jsx
const history = useHistory();
const goDetailPage = () => {
if(!isLogin && exhibition.exhibit_type === 2){
handleModalPremium();
} else{
selectGallery(exhibition);
history.push(`/gallerydetail/${exhibition.id}`);
}
}
if(isLogin){ // 로그인했다면? 좋아요를 했는지 안했는지에 따라서 하트 다르게 랜더링. 좋아요 클릭시 좋아요/좋아요 해제 가능
return(
//...
)
} else{ // 로그인 안 했다면? 좋아요 default 회색하트 랜더링. 클릭 시 로그인해주세요 모달창 띄우기
return (
//...
);
}
//Review.jsx
const history = useHistory();
const goDetailPage = () => {
selectReview(exhibition);
history.push(`/reviewdetail/${exhibition.id}`);
}
return(
{/* */}
{/* */}
{exhibition.title}
전시 기간: {exhibition.start_date} ~ {exhibition.end_date}
총 {exhibition.comments.length}개의 리뷰가 있어요
{/* */}
리뷰 쓰러가기
{/* */}
)
//GalleryDetail.jsx 내 3D 전시관 인입 버튼
const history = useHistory();
const goThreeDPage = () => {
handle3dExhibition(Number(location.pathname.substring(15)));
history.push(`/3dgallery/${Number(location.pathname.substring(15))}`);
}
return
// .........
{exhibitionInfo.exhibit_type ===2 ?
//
//
: null}
```
- 상세페이지에서 엔드포인트(exhibition.id) 받아와서 useEffect 내 axiosGet요청의 파라미터로 넘기기
- 'withRouter'는 react-router-dom에서 제공하는 기능. 이것을 컴포넌트 안에서 Props로써 활용할 수 있다. 클라이언트의 현재 라우팅 위치(엔드포인트)를 알아내기 위해 location 속성을 사용한다.
- 콘솔로 찍어가면서 pathname 내에서 exhibition.id만을 가져오고, 숫자타입으로 변환시켜주었다. —> `Number(location.pathname.substring(15))`
- **주의사항**! **getAxiosData로 인하여 exhibitionInfo가 상태값이 바뀌는 속도보다, 돔 랜더링이 먼저 되어서 자꾸 null이라 랜더링할 수 없다는 에러메세지가 뜬다**. 이 부분은 로딩시간을 700ms 을 두어, 로딩스피너가 돌아갈 때 setState가 작동하고 그 다음에 랜더링이 되는 것으로 수정하였더니 문제없이 랜더링이 되었다.
```jsx
import { withRouter } from 'react-router-dom';
const GalleryDetail = ({ location }) => {
const [exhibitionInfo, setExhibitionInfo] = useState(null);
useEffect(() => {
async function getAxiosData() {
setExhibitionInfo(await getExhibitionInfo(Number(location.pathname.substring(15))))
}
getAxiosData();
setTimeout(()=> {
setLoading(false);
}, 700)
}, []);
export default withRouter(GalleryDetail);
```
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.