※ 강의를 듣고 제가 이해한 것을 바탕으로 정리한 것이라서 오류가 있을 수 있습니다.
파라미터와 쿼리
페이지 주소를 정의 할 때, 우리는 유동적인 값을 전달해야 할 때도 있는데 이는 파라미터와 쿼리로 나뉘어질 수 있다.
예시)
파라미터: /profiles/kim
쿼리: /about?details=true
URL Params
/profile/kim 이런식으로 뒷부분에 username 을 넣어줄 때 해당 값을 파라미터로 받아와 보겠다.
아래는 그 기능을 하는 코드이다.
src/Profile.js
import React from 'react';
// 프로필에서 사용 할 데이터
const profileData = {
kim: {
name: 'kim',
description:
'프론트엔드 개발자 kim 입니다.'
},
gildong: {
name: '홍길동',
description: '전래동화의 주인공'
}
};
const Profile = ({ match }) => {
// 파라미터를 받아올 땐 match 안에 들어있는 params 값을 참조 한다.
const { username } = match.params;
const profile = profileData[username];
if (!profile) {
return <div>존재하지 않는 유저입니다.</div>;
}
return (
<div>
<h3>
{username}({profile.name})
</h3>
<p>{profile.description}</p>
</div>
);
};
export default Profile;
파라미터를 받아올 땐 match 안에 들어있는 params 값을 참조한다. match 객체안에는 현재의 주소가 Route 컴포넌트에서 정한 규칙과 어떻게 일치하는지에 대한 정보가 들어있다.
이제 Profile 을 App 에서 적용해볼건데 path 규칙에는 /profiles/:username 이라고 넣어주면 username 에 해당하는 값을 파라미터로 넣어주어서 Profile 컴포넌트에서 match props 를 통하여 전달받을 수 있게 된다.
src/App.js
import React from 'react';
import { Route, Link } from 'react-router-dom';
import About from './About';
import Home from './Home';
import Profile from './Profile';
const App = () => {
return (
<div>
<ul>
<li>
<Link to="/">홈</Link>
</li>
<li>
<Link to="/about">소개</Link>
</li>
</ul>
<hr />
<Route path="/" exact={true} component={Home} />
<Route path="/about" component={About} />
<Route path="/profiles/:username" component={Profile} />
</div>
);
};
export default App;
/profiles/kim과 /profile/gildong 경로로 직접 들어가보면 Profile 컴포넌트에서 입력한 데이터가 나타날 것이다.
Query
이번엔 About 페이지에서 쿼리를 받아오겠다. 쿼리는 라우트 컴포넌트에게 props 전달되는 location 객체에 있는 search 값에서 읽어올 수 있다. location 객체는 현재 앱이 갖고있는 주소에 대한 정보를 지니고 있다.
예시)
{
key: 'ac3df4', // not with HashHistory!
pathname: '/somewhere'
search: '?some=search-string',
hash: '#howdy',
state: {
[userDefined]: true
}
}
여기서 search 값을 확인해야하는데 이 값은 문자열 형태로 되어있다. 객체 형태로 변환하는건 직접 해주어야 한다.
이 작업은 qs 라는 라이브러리를 사용하여 쉽게 할 수 있다.
설치
npm install qs
이제 About 컴포넌트에서 search 값에있는 detail 값을 받아와서 해당 값이 true 일때 추가정보를 보여주도록 구현을 해보겠다.
src/About.js
import React from 'react';
import qs from 'qs';
const About = ({ location }) => {
const query = qs.parse(location.search, {
ignoreQueryPrefix: true
});
const detail = query.detail === 'true'; // 쿼리의 파싱결과값은 문자열입니다.
return (
<div>
<h1>소개</h1>
<p>이 프로젝트는 리액트 라우터 기초를 실습해보는 예제 프로젝트랍니다.</p>
{detail && <p>추가적인 정보가 어쩌고 저쩌고..</p>}
</div>
);
};
export default About;
/about?detail=true 경로에 들어가면 about 컴포넌트에서 구현해준 추가적인 정보가 나타난다.
'개발 공부한 내용 정리 > React' 카테고리의 다른 글
React- 리액트 라우터 부가기능 (0) | 2020.10.24 |
---|---|
React- 서브라우트 (0) | 2020.10.22 |
React- react router 프로젝트 준비 및 기본적인 사용법 (0) | 2020.10.20 |
React- react-async 로 요청 상태 관리하기 (0) | 2020.10.19 |
React- useAsync 커스텀 Hook 만들어서 사용하기 (0) | 2020.10.18 |