티스토리 뷰
728x90
2020/11/16 - [React] - [React] 08. React SPA와 Router 사용하기 01
# url 파라미터 사용하기
특정 id와 같은 정보를 사용하여 데이터를 조회할 때 파라미터 값을 사용하는데요!
먼저, 다음과 같은 Profile 컴포넌트를 만들어 username을 파라미터로 받아오겠습니다.
import React from "react";
const users = {
song : {
username : "송우든",
descirption : "프론트엔드 공부중입니다."
},
muk : {
username : "먹깨비",
descirption : "백엔드 공부중입니다."
}
}
const Profile = ({match}) => {
const { username } = match.params;
const profile = users[username];
if(!profile) {return <div>{username}존재하지 않는 사용자입니다.</div>}
return(
<div>
<h1> PROFILE PAGE </h1>
<label>{profile.username}님의 프로픨</label>
<br />
<label>{profile.descirption}</label>
</div>
);
};
export default Profile;
파라미터로 값을 받아올 때에는 match객체 안에 있는 param값을 참조합니다. match안에는 현재 컴포넌트가 어떤 경로 규칙에 의해 보이는지에 대한 정보가 들어 있습니다.
url에 파라미터를 지정할 때에는 : 을 사용합니다.
<Route component={Profile} path="/profile/:username" />
다음과 같이 추가하여 줍니다.
import React from "react";
import Home from "./component/Home";
import About from "./component/About";
import Profile from "./component/Profile";
import NotFound from "./component/NotFound";
import {
BrowserRouter as Router,Link,
Redirect,
Route,
Switch,
} from "react-router-dom";
export default function App() {
return (
<div>
<Router>
<Switch>
<Route component={Home} path="/" exact={true} />
<Route component={About} path="/about" />
<Route component={Profile} path="/profile/:username" />
<Route component={NotFound} path="/404" />
<Redirect from="*" to="/" />
</Switch>
<Link to="/about">about</Link>
<br />
<Link to="/profile/song"> song프로필</Link>
<br />
<Link to="/profile/muk"> muk프로필</Link>
</Router>
</div>
);
}

# url 쿼리 사용하기
어떤 데이터를 검색 또는 요청할 때 필요한 옵션을 전달할 때에 쿼리를 사용합니다.
먼저, 아래 명령어를 사용하여 qs라이브러리를 설치하여 줍니다.
npm install --save qs
쿼리는 location 객체에 search값에서 읽어올 수 있는데, location 객체는 현재 앱이 가지고 있는 주소 정보를 가지고 있습니다.
location 형태 예시
{
“pathname”: “/about”,
“search”: “?detail=true”,
“hash”: “”
}
이전에 설치해주었던 qs 라이브러리를 사용하여 문자열 형태인 search 값을 객체 형태로 쉽게 변경해줄 수 있습니다.
아래 예시는 About 컴포넌트에서 search 값에 있는 detail 정보를 받아와 각각에 쿼리 값에 맞게 화면을 그려주는 코드입니다.
import React from "react";
import qs from "qs";
const About = ({location}) => {
const query = qs.parse(location.search, {
ignoreQueryPrefix : true
});
const showDetail = query.detail === 'true';
return(
<div>
<h1> ABOUT PAGE </h1>
{showDetail && <p>showDetail 값이 true 입니다.!</p>}
{!showDetail && <p>showDetail 값이 false 입니다.!</p>}
</div>
);
};
export default About;

728x90
'REACT' 카테고리의 다른 글
[React] 11. Router를 사용해서 뉴스뷰어 만들기 (0) | 2020.11.29 |
---|---|
[React] 10. Context API 사용해보기 (0) | 2020.11.25 |
[React] 08. React SPA와 Router 사용하기 01 (0) | 2020.11.16 |
[React] 07. React에 styled-component 사용하기 (0) | 2020.11.13 |
[React] 06. React Hooks 사용하기 (0) | 2020.11.11 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크