mangocoder
[React] 버전5 → 버전6 바뀐 점 본문
반응형
SMALL
https://kyung-a.tistory.com/36
react-router-dom v6 업데이트 후 달라진 점 (ft. Prompt 창 띄우는 법)
불과 몇 달전만 해도 문제없이 잘 쓰고 있었던 react-router-dom 리액트 공부를 다시 시작하면서 router 파트를 복습삼아 진행했는데 분명 그대로! 평소에 썼던거처럼 작성했는데 에러가 뜨는거다! 보
kyung-a.tistory.com
1. Switch → Routes 네이밍 변경
Switch란?
여러 Route를 감싸서 그 중 규칙이 일치하는 라우트 단 하나만을 렌더링
( 아무것도 일치하지않으면 Not Found 페이지로 구현할 수 있었다.)
여러 개를 감싸는 부모 컴포넌트 네이밍으로 변경 됨
// v5
<Switch>
<Route />
<Route />
</Switch>
// v6
<Routes>
<Route />
<Route />
</Routes>
2. exact 옵션 삭제
기존에 루트( ‘/’) 페이지 같은 경우 모든 페이지들이 다 불러오는 현상이 있었는데
V6 부터는 이 옵션이 삭제되고 알아서 정확히 매칭되는 컴포넌트를 보여준다.
만약 하위경로에 여러 라우팅을 매칭시키고 싶다면 URL 뒤에 *을 사용하여 이용할 수 있다.
<Route path="main/*" />
3. 에서 컴포넌트 렌더링
컴포넌트 렌더링을 하기 위해서 사용했던 component, render(JSX 자체를 렌더링 하는 것) 속성 네이밍이 element로 바뀌었다.
// v5
<Route path='/user' component={UserInfo} />
<Route path='/user' render={routeProps => (
<UserInfo routeProps={routeProps} isLogin={true} />
)} />
// v6
<Route path="/user" element={<UserInfo />} />
<Route path="/user" element={<UserInfo isLogin={true} />} />
4. URL Params 읽는 법 (match 객체)
기존에는 파라미터를 받기 위해서 match객체를 사용했는데 V6에서는 useParams를 사용한다.
// v5
const Profile = ({ match }) => {
// v5에선 파라미터를 받아올 땐 match 안에 들어있는 params 값을 참조했었습니다
const { username } = match.params;
}
<Route path="/profiles/:username" component={Profile} />
// v6
import { useParams } from 'react-router-dom';
const Profile = () => {
const { username } = useParams();
}
<Route path="/profiles/:username" element={<Profile />} />
5. Query 읽는 법 (location 객체)
V5 에서는 라우트 컴포넌트에게 전달되는 location 객체에 있는 search 값에서 읽어올 수 있었다.
그리고 문자열을 객체 형태로 변환하기 위해서 qs라는 라이브러리를 사용해야만 했다.
// v5
import qs from 'qs'
const About = ({ location }) => {
const query = qs.parse(location.search, {
ignoreQueryPrefix: true //쿼리 접두사 무시
}
const detail = query.detail === 'true'; // 쿼리의 파싱 결과값은 문자열
return (
<div>
{detail && <p>해당 경로로 들어오면 보이는 텍스트입니다</p>}
</div>
)
}
// v6
import { useLocation } from 'react-reuter-dom';
const About = () => {
const { search } = useLocation();
//현재 지금 경로가(search) '?detail=true' 인지 확인
const detail = search === '?detail=true';
return (
<div>
{detail && <p>해당 경로로 들어오면 보이는 텍스트입니다</p>}
</div>
)
}
반응형
LIST
'React(리액트)' 카테고리의 다른 글
[React] 스프링 연동 (1) | 2022.09.29 |
---|---|
[React] Key (0) | 2022.08.31 |
[React] JSX (0) | 2022.08.30 |
[React] 컴포넌트 (0) | 2022.08.29 |
[React] render , DOM (0) | 2022.08.29 |
Comments