
App.js 에 react-router-dom 을 사용해 페이지를 이동시키고 있다.
그런데 post(게시글) 에는 번호가 부여되고, postDetail 에는 해당 게시글만 보여야 한다.
그래서 App.js 에서 route 하면서
// App.js
<Route path='/post/:id' element={<PostDetail />} />
이렇게 해서 해당 게시글로 이동하도록 했다.
posts 컴포넌트에서는 나타난 게시글을 클릭했을 때 props 로 postId 를 받도록했다.
// Posts.jsx
function handlePostDetail(props){
navigate(`/post/${props}`)
}
그런데 postDetail 에서는 props를 어떻게 받아야 하는지 모르는 매우매우 심각한 상황이 생김.
클릭된 게시글인 postDetail 페이지가 rendering 되면서 useEffect 가 axios.get()을 사용해 게시글을 가져올 때 주소에 해당 게시글의 id가 입력되어야하는데... 그래야 해당 게시글을 가져올 수 있는데...
Link 를 사용해도 안 되고, 뭐 어떻게 component 에 state 를 줬는지 다들 잘되는데 나만 안됨.
useLocation 을 사용한다.
의 navigate 에 state 를 이용해 data 를 넘겨준다.
// Posts.jsx
function handlePostDetail(props){
navigate(`/post/${props}`, {
state:{
postId:props
}
})
}
그리고 postDetail 에서는 useLocation 을 활용해 navigate 가 보낸 state 를 가져온다.
// PostDetail.jsx
const postProps = useLocation()
...
useEffect(()=>{
axios.get(`/post/${postsProps.state.postId}`)
.then
...
따란~!
쉽죠?

이렇게 되면 useLocation 을 이용해 가져온 data를 가지고 댓글을 불러올 때도 훨씬 쉬워진다.
해당 댓글을 가져올 때, PostDetail 에서는 Reply component를 가져올 텐데,
// PostDetail.jsx
...
<Reply postId={postProps.state.postId}/>
...
그 때 Reply component 에 저런식으로 props 를 넘겨주면 reply 는 props 형태로 받을 수 있다. 그 뒤는 아주 쉽다.
나는 useLocation 을 몰라서 3시간을 혼자...
