[react]동적 라우팅 (match)

Kyungoh Kang·2020년 12월 20일
0

wecode15

목록 보기
14/20

동적라우팅

url 파라미터를 이용해 동적으로 라우팅을 하는 기능 => 뒤의 url에 따라서 다른 값을 렌더해주는 거

history, location, match 세가지 컴포넌트를 이용해 동적 라우팅을 할 수 있다.

  1. 라우터에서 컴포넌트의 경로에 :id를 추가해준다
<Route exact path="/monsters/detail/:id" component={MonsterDetail} />```
  1. fetch나 push 하는 경로에 id값을 추가로 입력해준다.
    fetch(
          `https://jsonplaceholder.typicode.com/users/${this.props.match.params.id}`
        )
          .then((res) => res.json())
          .then((res) =>
            this.setState({
              data: res,
            })
          ); ```
  2. ComponentDidUpdate(props, state){}를 이용해 렌더 될 때 다시 데이터를 받아올 수 있게한다.
  • 이 때 조건을 걸어준다.
 componentDidUpdate(prevProps) {
    if (prevProps.match.params.id !== this.props.match.params.id) {
      this.getData();
    }
  }```
  

- 이렇게 유동적으로 id값을 변경시켜서 사용자가 클릭한 내용을 렌더해 보여줄 수 잇따.
  
      

0개의 댓글