Path Parameter_React

miin·2021년 10월 13일
0

React

목록 보기
16/52
post-thumbnail

Path Parameter

  • 라우트 경로에 특정값을 넣어 해당하는 페이지로 이동할 수 있다
    1) Path Parameter
    라우트 경로 끝에 들어가는 각기 다른 id값들을 저장하는 매개변수
localhost:3000/product/45
localhost:3000/product/125
-> <Route exact path='/product/:id' component={productDetail} />

: : Path Parameter가 붙는것을 의미
id: 해당 Path Parameter의 이름을 의미(변수명)


1.

  • 리스트 페이지의 개별상품을 클릭하면 onClick 이벤트시 발생하는 push 함수(this.props.history.push)를 통해 /product/1로 이동
  • url이 /product/1로 변하면, route 컴포넌트에 정의되어 있는 path='/product/:id에 따라 productDetail 컴포넌트가 마운트됨
    url("http://localhost:3000/product/1")
  1. productDetail 컴포넌트에서는 백엔드에 id가 1인 아이템에 대한 정보를 요청
componentDidMount() {
  const id = this.props.match.params.id
  fetch(`http://123.456.33:8000/products/${id}`)
  	.then(res => res.json())
  	.then(res => this.setState({ data: res }))
}
  1. 서버에서 가져온 데이터(res)를 setState함수를 통해 state 객체에 저장하고,
    state객체에 담긴 데이터로 컴포넌트 UI를 render 해준다(UI를 그려준다)

history, match, location객체

  • productDetail 컴포넌트의 componentDidMount 메서드에서 백엔드에 id가 1에 해당하는 정보를 요청했다.
    하지만 1은 url에 담겨있다 productDetail 컴포넌트에서 이 객체를 사용하여 id값을 가져올 수 있다
  • Routes.js의 Route 컴포넌트의 component 프로퍼티에 직접 연결되어 있는 하위 컴포넌트는 history, location, match 3가지 객체를 props를 통해 제공 받는다
  • history, location, match는 Route 컴포넌트가 component 프로퍼티에 연결 되어있는 컴포넌트에 제공하는 객체
//Routes.js
<Route exact path='/product/detail/:id' component={ProductDetail} />
  //ProductDetail.js
  render(){
  	console.log(this.props)
  //{ history: {}, location: {}, match: {}, ...}
  	return(
      ...
     );
   }
  • history객체는 페이지 이동을 위한 여러 메서드들을 담고 있다(ex, onClick={() => this.props.history.push('main')})
  • location 객체는 현재 url 경로에 관한 정보를 담는다
  • match 객체는 path parameter에 관한 정보를 담는다

withRouter HOC

  • Router에 연결돼 있어야 3개의 객체들을 제공받지만, 연결이 안되어 있어도 사용하는 방법은 withRouter 함수를 사용하는 것이다
  • 인자로 컴포넌트를 받고, 해당 컴포넌트에 3가지 객체를 추가한 컴포넌트를 반환한다
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.match.params.id

  • match 객체를 이용하여 url에 담겨있는 id값을 가져올 수 있다
    path parameter로 명시해둔 값은 match객체에 담기기 때문이다
// ProductDetail.js
// current url -> localhost:3000/product/1

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

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

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

  • <Link to={`/monsters/${this.props.id}`}>
      <div>
       <img
         src={`http://rovoo.org/${this.props.id}?set=sdf`}
         alt="" 
        />
        <Card id={this.state.data.id} 
        	  name={this.state.data.name}/>
        <h2>{this.props.name}</h2>
        <p>{this.props.email}</p>
      </div>
     </Link>
  • this.props.history.push(`/monster/detail/${id}`)
  • config.js
    //반복되는 url을 따로 구조분해할당 해서 import 하기(ex)메뉴바)
    export const API = 'http://10.58.43:8000';
    
  • import { API } from '../../config';
    componentDidMount(){
    	fetch(`${API}/products/2`)
        	.then(res => res.json())
            .then(({ result: data }) => {
            	if (data) {
                	this.setState({ data });
                }else{
                	console.log('not found');
                }
                });
    }
1) onClick 
2) 페이지 이동
this.props.history.push(`/monsters/detail/${id}`)
3)경로찾기
path= "/monster/detail/:id"
4)id값 받아서 fetch
fetch(`${API}/${this.props.match.params.id}`)

0개의 댓글