TIL44.동적라우팅

조연정·2020년 11월 15일
0
post-thumbnail

'동적라우팅'을 이용해서 상품리스트페이지에서 해당 상품을 클릭하여 상세페이지로 넘어가보자.

동적라우팅(Dynamic Routing)이란?

동적라우팅이란 라우트의 경로에 특정 값을 넣어 해당 페이지로 이동할 수 있게 하는 기능을 말한다.
'Query parameters', 'URL parameters' 두가지 방법을 통해 유동라우팅을 구현할 수 있다.
url 의 path와 qurery string 을 이용하여 어떤 정보를 불러올지 결정한다.

http://a.com/coffee?id=1

'http://'은 프로토콜, 'a.com'은 도메인, 'coffee'는 path, 'id=1'은 query string이라고 부른다.

라우트로 설정한 3가지 props

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

  • history: history 객체의 push, replace를 통해 다른 경로로 이동시키거나 앞 뒤 페이지로 전환할 수 있다.(this.props.hsitory.push('/page')

  • location: 현재 경로에 대한 정보와 url쿼리에 대한 정보를 가지고 있다.

  • match: 어떤 라우트에 매칭이 되었는지와 params(/detail/:id)정보를 가지고 있다.

제품리스트페이지에서 상세페이지로 이동

동적라우팅이 가장 많이 사용되는 곳이 리스트 페이지에서 상세페이지로 이동될 때이다.리스트 페이지에서 어떤 상품을 클릭했는지 파악하고 API를 호출하는 것이 포인트이다.

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/ProductDetails/ProductDetails";
import Navbar from "./Components/Navbar/Navbar";

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

export default Routes;

상세페이지path에 id라는 params를 추가한 라우트가 필요하다.

card.js

import React, { Component } from "react";
import "../CardList/CardList.scss";
import { withRouter } from "react-router-dom";

class Card extends Component {
  render() {
    const { img, taste, company, name, price, id } = this.props;
    return (
      <div
        onClick={() => this.props.history.push(`/ProductDetails/${id}`)}
        className="cardContainer"
      >
        <div className="imgContainer">
          <img src={img} alt="product_pic" />
        </div>
        <div className="taste">
          <h2>{taste}</h2>
        </div>
        <div className="productInfo">
          <h3 className="companyName">{company}</h3>
          <h2>{name}</h2>
          <h3 className="price">{`$${price}`}</h3>
        </div>
      </div>
    );
  }
}

export default withRouter(Card);

ProductList 페이지 안에서 Card 컴포넌트가 렌더된다. 라우팅을 사용하기위해서 withRouter를 import 해주고, export 에서 감싸준다.
cardContainer에 onClick 이벤트로 해당 card의 props의 id 값이 담긴 url 주소로 push 해준다.(상세페이지로 이동)

ProductDetails

componentDidMount() {
    fetch(APIProductDetails + `/${this.props.match.params.id}`)
      .then((res) => res.json())
      .then((res) => {
        this.setState({
          productSummary: res.foundProduct,
          coffee: res.foundProduct.coffees,
          roaster: res.foundProduct.coffees.roasters,
        });
      });
}
//컴포넌트가 마운트 되었을 때 해당 id의 json data를 state에 업데이트 해준다.




profile
Lv.1🌷

0개의 댓글