본문 바로가기
  • 삽질하는 자의 블로그
React/React-Route

3. 쿼리 매개변수를 사용해, 아이템 정렬하기 [ useHistory, useLocation , URLSearchParams ]

by 이게뭐당가 2022. 12. 20.

버튼을 눌러 정렬을 시켜보자.

버튼을 누르면, "URL 을 이동(쿼리 매개변수만을 추가한)" 을 통해 		[ useHistory ]

쿼리 매개변수를 불러오고 							[ useLocation ]

불러온 매개변수를 가공하여 						[ URLSearchParams ]

정렬 하려는 조건을 알아내고, 그것에 맞추어 정렬 하는 코드를 만들어보자

 

1. 쿼리 매개변수에 대하여 , [ useHistory ]

쿼리 매개변수는 URL ? 다음에 오는 키와 값들을 의미한다.

https://localhost:3000/Items/Item-detial?type=post  바로 이부분!

 

화면을 전환시키지 않고, 새로운 값을 받을 수 있는유용한 기능이다.

 

간단하게 생각해서 URL 뒤에 ? 를 붙이고 키와 밸류를 넣으면 된다.

 

그렇다면 useHistory 를 사용한다면, 쿼리 매개변수를 만들 수 있다.

 

 

2. 불러온 매개변수의 추출 , [ useLocation ]

 

불러온 매개변수를 추출하고싶다.

 

현재의 URL 을 가져오는 훅인, useLocation 을 사용하도록 한다.

 

const Component= ()=>{
	const location = useLocation()
    
    console.log(location.search)	// ?type=post
}

 

3. location.search 의 가공 [ URLSearchParams ]

 

결과로 나온 값을 사용하기에는, 너무 불편함이 따른다.

 

URLSeartchParams 자바스크립트 내장메서드를 사용하여, 키와 값을 분리한다.

 

const Component= ()=>{
	const location = useLocation()
    
    const params = new URLSearchParams(location.search)	// 키와값이 담긴 객체로 변환시키고
    
    const paramsValue = params.get("type")		// .get("키") 를 이용하여 value 를 추출
}

 

4. 정렬 함수 만들기

 

const reArrangeHandler = (items, arrangeRule) => {
	return items.sort((A,B) => {
    	if(arrangeRule){
        	return A.content > B.content ? 1 : -1
        } else {
        	return B.content > A.content ? 1 : -1
        }
    })
}

 

5. 조합하여 최종적인 [ 쿼리 매개변수를 사용한, 아이템 정렬 만들기]

 

 

const reArrangeItems = (items, isAscending) => {	// 외부에, 헬퍼함수 정의(정렬용)
    return items.sort((A, B) => {
        if (isAscending) {
            return A.content > B.content ? 1 : -1;
        } else {
            return B.content > A.content ? 1 : -1;
        }
    });
};

const Component = ()=>{
    const itemsState = useSelector((state) => itemsState.itemSlice.allItems);

    const allItems = [...itemsState];    // State 빼서사용

    const location = useLocation()
    const arrangRuleObj = new URLSearchParams(location.search
    const arrangeRule = arrangRuleObj.get("rule")		// 쿼리 키가 rule 이므로

    let isAscending = arrangeRule === "asc"

    reArrangeItems(allItems, isAscending)		// 객체변화는, 원본변화이므로

    const arrangeHandler = () => {
        history.push("/items?rule=" + (isAscending ? "desc" : "asc")); // 버튼을 누르면, 쿼리파라미터 생성
    };

    return (
        ...
        <button onClick={arrangeHandler}>
            {isAscending ? "내림차순" : "오름차순"}
        </button>
    ...
    )

    }

댓글