React : ) Dynamic Routing & Path Parameter

이선호·2021년 10월 17일
1

React

목록 보기
6/7
post-thumbnail

Routing이란?

라우팅 이란, 다른 경로(url 주소)에 따라 다른 화면를 보여주는 것이다.
프로젝트에서 react-router-DOM 라이브러리를 사용해 라우팅을 구현했었다.
지금까지 해온 라우팅 방법으로는 완전히 정해진 경우(정적, static)에 대해서만 경로를 표현 했었다.

// Routes.js
const Routes = () => {
  return (
    <Router>
			<Nav />
      <Switch>
        <Route exact path="/" component={App} />
        <Route exact path="/users" component={Users} />
        <Route exact path="/products" component={Products} />
        <Route path="*" component={NotFound} />
      </Switch>
			<Footer />
    </Router>
  );
};
// 
//"/"         => <App />
//"/users"    => <Users />
//"/products" => <Products />

Path Parameter

<Router>
    <Switch>
        <Route exact path='/product/:id' component={productDetail} />
    </Switch>
</Router>
  • : 는 Path Parameter 가 올 것임을 의미합니다.
  • id 는 해당 Path Parameter 의 이름을 의미합니다. 변수 명을 짓듯이, 임의의 이름을 지정해줄 수 있습니다. ex) :productId

this.props.match.params.id

❓ 어떻게 URL에 담겨있는 id값을 가져올 수 있을까? ❓
match 객체를 이용하여 가져올 수 있다.
Path Parameter 로 명시해둔 값은 match 객체에 담기기 때문

// curent url -> localhost:3030/product/1

class ProductDetail extends React.Component {
  ...
  render() {
    console.log(this.props.match.params.id);  // 1
    retrun (
      ...
    );
  }
}

따라서 componentDidMount 메서드에서 해당 id 값을 통해 서버에 요청을 보내는 것을 통해 원하는 정보를 받아올 수 있다.

fetch(`${API}/${this.props.match.params.id}`)
  .then(res => res.json())
  .then(itemData => ... );

history, match, location 객체

Routes.js 에서 Route 컴포넌트 프로퍼티에 직접 연결되어 있는 하위 컴포넌트는
history, location, match 3가지 객체를 props 를 통해 제공 받는다.

  • history 객체는 페이지 이동을 위한 여러 메서드들을 담고 있습니다.(ex, push)
  • location 객체는 현재 url 경로에 관한 정보를 담습니다.
  • match 객체는 Path Parameter 에 관한 정보를 담습니다.

Q. Route 에 연결되어 있지 않는 컴퍼넌트가 history, location, match 객체를 쓰고 싶을때 방법은?

A. withRouter HOC를 쓰면 해당 컴포넌트에 3가지 객체를 추가한 컴포넌트를 반환한다.

withRouter HOC쓰는 법

📍 import와 export에 withRouter HOC 쓰기 📍

import { withRouter } from 'react-router-dom';

class Payment extends React.Component {
   render() { console.log(this.props) }
      // { history: {}, location:{}, match:{}, ... }
	return( ... )
    }
}

export default withRouter(Payment);

정리

  • 리스트 페이지의 개별 상품을 클릭
    this.props.history.push("/product/1") 로 상세 페이지로 이동합니다.
  • 상세 페이지로 이동하면 url은 "http://localhost:3000/product/1" 과 같이 변경되어 있습니다.
  • 페이지에 필요한 데이터를 CDM 에서 fetching 합니다.
  • 필요한 id는 URL에 존재하므로 this.props.match.params.id 에서 가져올 수 있습니다.
  • 해당 id를 가지고 백엔드에서 만들어준 API를 호출합니다.
componentDidMount() {
  const id = this.props.match.params.id
    fetch(`http://123.456.123.123:8000/products/${id}`) // 1
    .then(res => res.json())
    .then(res => this.setState({ data: res }))
        }
  • 서버에서 가져온 데이터(res)를 컴포넌트의 state 객체에 저장해 줍니다.
  • state 객체에 담긴 데이터로 컴포넌트 UI 를 render 해줍니다.

0개의 댓글