TIL no.39 - React 동적라우팅

김종진·2021년 2월 20일
0

React

목록 보기
7/17

동적라우팅

라우트의 경로에 특정 값을 넣어 해당 페이지로 이동할 수 있게 하는 것

React Router에서는 유동 라우팅 기능을 구현할 수 있다.

2가지 방법이 있다.
1. Query parameters
2. URL parameters

프로젝트 중 상품 리스트 페이지에서 상세 페이지로 넘어가는 로직을 구현하고자 한다.
"하지만 상세페이지에서 이전에 리스트 페이지에서 어떤 상품을 클릭했는지 어떻게 알고 API를 호출할까?"

라우트로 설정한 컴포넌트의 3가지 props

라우트로 설정한 컴포넌트는 기본적으로 객체형태의 3가지 props를 전달받는다.

  1. history
    이 객체를 통해 push, replace 를 통해 다른 경로로 이동하거나 앞 뒤 페이지로 전환 할 수 있다.

  2. location
    이 객체는 현재 경로에 대한 정보를 지니고 있고, URL 쿼리 (/company_list?category=3)에 대한 정보도 가지고 있다.

해당 URL에서 필요한 key값을 추출하여 백엔드와 데이터 통신을 하고 백엔드와 통신한 데이터로 원하는 정보를 페이지에 담을 수 있다.

  1. match
    이 객체에는 어떤 라우트에 매칭이 되었는지에 대한 정보와 params (/company_detail/:id) 정보를 가지고있다.

동적 라우팅 사용

상품 리스트에서 선택한 상품 페이지로 이동

Routes.js

import React, { Component } from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import ProductList from "./Pages/ProductList/ProductList";
import ProductDetails from "./Pages/ProductDetail/ProductDetail";
import Navbar from "./Components/Navbar/Navbar";

class Routes extends Component {
  render() {
    return (
      <Router>
        <Navbar />
        <Switch>
          <Route exact path="/ProductList" component={ProductList} />
          <Route exact path="/ProductDetail/:id" component={ProductDetail} />
        </Switch>
        <Footer />
      </Router>
    );
  }
}

export default Routes;

상세 페이지의 path에 path="/ProductDetail/:id" 이와 같이 :id라는 경로를 추가로 설정해준다.

:id 는 params 경로이다.

ProductMain.js

// 선택한 상품 페이지로 넘어가는 함수
  gotoDetail = (id) => {
    this.props.history.push(`/productDetail/${id}`);
  };

...

<div className="itemImg">
   <img alt="상품" src={product.image}
    onClick={() => gotoDetail(product.id)}
   />
</div>

특정 상품의 이미지를 클릭하면 해당 상품의 id를 인자로 받아 gotoDetail 함수를 실행시킨다.
라우트의 이동 경로가 /productDetail/${id}로 설정되어있는데 어느 상품으로 이동할지 정해준다.

여기서 사용된 방법이 URL parameters이다.

ProductDetail.js

class ProductDetail extends Component {
  render() {
    return (
      <div>
        <ProductInfo root={this.props.match.params.id} />
        <ProductReview />
        <CardList />
      </div>
    );
  }
}

export default ProductDetail;

해당 상품 상세 페이지 컴포넌트에서 this.props.match.params.id를 통해 해당 값을 가지고 올 수 있다.
실제 데이터를 받아서 렌더링 하는 컴포넌트에 root로 값을 내려준다.

ProductInfo.js

  state = { selectdItem: [] }
  
  componentDidMount() {
    this.onRequestProductDetail();
  }
  
  onRequestProductDetail = () => {
    fetch(`http://10.58.2.60:8000/products/${this.props.root}`)
      .then((response) => response.json())
      .then((data) => {
        this.setState({
          selectdItem: data,
        });
      });
  };
  

해당 상품의 정보를 보여주는 컴포넌트가 렌더링 될 때 onRequestProductDetail() 함수를 실행 시켜 내려 받은 this.props.match.params.id를 받아 해당 상품의 API 정보를 호출 한다.

fetch로 받아온 해당 상품의 Data를 얻어 화면에 나타낸다.

두 가지 방법의 사용의 차이점

String parameters

해당 페이지에서 여러 정보가 필요한 경우
Query parameters를 사용하고 싶은 경우 routes.js를 수정해야 하기 때문에 유지 보수 측면에서 좋지 않다고 판단 될 경우
필터링을 하고 싶은 경우

Query parameters

특정한 resource를 식별하고 싶은 경우. 즉, 하나만 딱 필요한 경우

profile
FE Developer

0개의 댓글