Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Tags
more
Archives
Today
Total
관리 메뉴

바스키아

Router) 파라미터와 쿼리 본문

JS/React

Router) 파라미터와 쿼리

바스키아1 2019. 8. 30. 11:18

파라미터랑 쿼리는 통해서 주소를 통해 동적인 값을 읽어와야 할때...사용한다..

 

우선 밑에 형식이다.

 

Query는 주로 검색조건이용할때 많이 사용한다.

 

두형식으로 우선 예제를 만들어볼껀데 URL Parameter먼저

 

Profile.js를 만들어보자

 

import * as React from 'react';
 
 
const profileData = {
    beom :{
        name : 'beom',
        description : "Front Engine ...MyInfo ...etc"
    },
    homer : {
        name : '호머 심슨',
        description : '심슨가족 아빠 주인공'
    }
}
function Profile({ match }) {
    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;

우선 const 변수선언후 profileData이름에 json형식의 데이터를 넣어줬어.

 

그리고 Profile이라는 함수를 정의했는데. 저기서 처음보는게 나올꺼야 match (나도 처음봄)

function Profile({ match }) {
    const { username } = match.params;
    ...
    ...
    

우선 도큐먼트 주소야

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/match.md

읽어보면 도움이 될까? 

 

match는 어떻게 route path 와 매치된 URL에대한 정보를 match object는 가지고 있데... (번역수준 ㅈㅅ)

그리고 match는 다음과 같은 프로퍼티를 가지고 있데

이정도는 너네가 해석할수 있잖아 그치?

즉 match는 라우터 통해서 컴포넌트 불러왔을때 우리가 사용할수 있는거야 우리는 위 그림에 path 프로퍼티를 한번 보고 app.js로 넘어가자.

  <Route path="/profiles/:username" component={Profile} />

라우터에 component 를 Profile로 잡아놓았고 path에  url 파라미터를 ":" 표시후 username으로 주었어

즉  username 부분에 입력되는 파라미터를 Profile컴포넌트에 {match} 로 넘겨주는거야 그럼 

Profile.js에서는 this.props.match 처럼 match를 받아서 사용하는거지. 이해가 될지 모르겠네.

이딴식 왜 가는하냐고?  위에 도큐먼트에 그렇게 사용가능하다 써있으니까!!!!!!!!!!!토달지마

 

 이 싸이클이 이해가 가?? 실행을 하면 다음과 같이 출력이되

if(!profile){
    return <div>존재하지 않는 사용자입니다. </div>
}

 

profileData 에 없는 정보인 파라미터를 url에 입력하면?? 위에처럼 나와야하는데 과연....?

그런넘은 존재하지 않는데 ㅎㅎ

 

========================================================================================================================================================

 

이번엔 쿼리형식으로 사용해보자

 

쿼리를 조회할때는 props를 통해서 location을 받아와서 조회할수가 있다.

 

import React from 'react'
 
function About({ location }) {
    return (
        <div>
            <h1>라우터 체인지</h1>
            <p>이곳은 라우터 체인지된 ABOUT 입니다.</p>
        </div>
    );
}
export default About;
console.log(location); 

찍어보면 어떻게 출력되는지 확인좀 해보자

url 에 옵션의 의미인 "?" 를 달아준후 a = 1 쿼리형식으로 접근을 하니 콘솔이 이렇게 떴다..

 

searh: "?a=1" -->이것을 추출해서 사용해줘야하는데...

npm i qs

이녀석을 통해 추출해줄수 있다고한다.

import React from 'react';
import qs from 'qs';
 
function About({ location }) {
    console.log(location);
const query = qs.parse(location.search,{
    ignoreQueryPrefix : true
});
    console.log(query);
    return (
        <div>
            <h1>라우터 체인지</h1>
            <p>이곳은 라우터 체인지된 ABOUT 입니다.</p>
        </div>
    );
}
export default About;

qs 라이브러리고 search를 추출해서 사용한다.

만약 ignoreQueryPrefix : true 처리를 해야 ?표시가 없는 온전한 객체로 받을수 있다.

이렇게 말이다..

 

이제 마지막 예제로 detail 값이 true라는 쿼리를 받아오면 내용을 출력하겠다라고 만들고싶다면 아래와 같다.

 

import React from 'react';
import qs from 'qs';
 
function About({ location }) {
    console.log(location);
const query = qs.parse(location.search,{
    ignoreQueryPrefix : true
});
 
    const detail = query.detail === 'true'
    console.log(query);
    return (
        <div>
            <h1>라우터 체인지</h1>
            <p>이곳은 라우터 체인지된 ABOUT 입니다.</p>
            {detail && <p>detail 값이 true입니다!.</p>}
        </div>
    );
}
export default About;

detail=true 로 받아올때는 boolean형식이 아닌 string 형식으로 오는것이기 때문에

query.detail === 'true' 로 입력해주어야 하는것을 명심하자(쿼리로 받은건 문자열로 비교해주어야하는걸 명심)

 

'JS > React' 카테고리의 다른 글

리액트 시작하기  (0) 2019.08.31
Router) Router의 부가기능 (.feat history, withRouter)  (0) 2019.08.30
Router) 서브 라우트 만들기  (0) 2019.08.29
Router) 사용하기  (0) 2019.08.29
Router) What is..... React - Router  (0) 2019.08.26