Silver Library (Archived)
만약 useParams 로 상세페이지 구현에서 막힌다면... 본문
우선 간과한 것이 있다면, Route 부분입니다.
이 useParams, 이제 좀 쉬고 진정된 상태에서 다시 보니까 뭔가 눈에 들어오기 시작합니다.
그리고 충격적인 문구.
The useParams hook returns an object of key/value pairs of the dynamic params from the current URL that were matched by the <Route path>. Child routes inherit all params from their parent routes.
!!!!
그랬습니다. 아무리 '대체 무슨 원리로 상세페이지로 들어가면, 저건 항상 id 값이 주어지는 걸까?' 에 대한 깊은 의문을 가지면서, props 인가? DOM manipulation 의 일종인 것 같은데?
저건 무슨 원리로 데이터가 동적으로 전달 되는 걸까? 그것도, 딱 저 페이지에만?
이란 의문은 들지만, 당시 마음이 급했던 필자는 그런 것 조차 보이질 않았습니다.
결국, Route 와 함께하는 react-router-dom hook 였다는 결론입니다.
그러니, Route 에 대한 의문은 계속 들었지만, 거기에 스코프를 두지 못해서 동작 원리에 대한 확신을 가지지 못했던거죠.
import * as React from 'react';
import { Routes, Route, useParams } from 'react-router-dom';
function ProfilePage() {
// Get the userId param from the URL.
let { userId } = useParams();
// ...
}
function App() {
return (
<Routes>
<Route path="users">
<Route path=":userId" element={<ProfilePage />} />
<Route path="me" element={...} />
</Route>
</Routes>
);
}
자세히 보면 Route path=":userId" element={<ProfilePage />} 라는게 보일겁니다.
네, useParams 는 바로 저 ProfilePage 라는 곳에서 선언이 되면, Route path=":userId" 를 감지해서,
object of key/value paris of dynamic params from the current URL that were matched by the '<Route path>' 를 실현하게 됩니다. 그리고 정말, 해당 지점 이후로 선언된 child routes 들은 모든 parmas 를 승계하게 됩니다.
결론:
in this code, the :userId in the <Route path=":userId" element={<ProfilePage />} /> component represents a URL parameter, which can be accessed using the useParams hook from react-router-dom. When the user navigates to a URL that matches the /users/:userId pattern, the useParams hook will return an object with a userId property that corresponds to the value of the :userId parameter in the URL.
역시 사람은 필요한 만큼 적절히 쉬어줄 필요가 있어보입니다. 피로 누적은 무서운거에요.