[React] Router props

예리에르·2021년 4월 14일
1

React

목록 보기
2/17

도입배경

특정 페이지로 넘어갈 때 단순히 페이지만 이동하는 것이 아니라 특정 데이터를 같이 넘길수 있는 방법이 없을까 고민하였다. 그래서 react-router-dom 중 하나인 Link 방법을 생각하였다.

component -> component 로 렌더링 될때 값을 넘겨주는 것이 아닌 Routing으로 component가 렌더링 될때 값을 어떻게 넘겨 줄까?

URL 이동하기

  • Link : <a></a> 와 같은 역할을 한다. 하지마 SPA특성상 새로고침이 일어나면 안되기 때문에 새로고침이 일어나지 않게 이동시켜준다.

  • history.push : Route는 기본적으로 history, location, match 를 넘겨주는데 인자를 넣어주면 해당 인자를 새로고침 없임 넘겨준다.

routing한 component들은 3가지 방법으로 읽기 전용 데이터를 전달 받는다. history, location, match라는 3가지 읽기전용 데이터를 전달받는다.

1. Router에 parmas 입력하기

<Route
  exact
  path="/fooder/:userId"
  component={Auth(FooderPage, true)}
/>

직접 입력한 params는 match.params를 통해 접근 할 수 있다.

console.log(props.match.params.userId) // path 에 담겨져있던 params

2. Router에 object형태 값 넘겨주기

<Link
  to={{
    pathname: `/fooder/4`,
    state: { username: fooder.nickname },
  }}
>
  {/* <Link to={`/fooder/${fooder.id}`}> */}
  <Meta
    avatar={
      <Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />
    }
    title={fooder.nickname}
    style={{ height: '50px' }}
  />
</Link>

object롤 확장하게 되면 pathname, query, hashname, state 이렇게 4가지 key를 가질 수있다. pathname은 주소가들어가고 state에 원하는 데이터를 넣어준다.

console.log(props.location.state.username) // state에 담아줬던 값

3. history.push의 props넘겨주기

  • history.push로는 routing만 가능하고 props가 불가능하다고 생각하여 Link를 사용하였는데 글을 정리하다 보니 history.push에서도 routin에서 props가 가능하였다.
<button onClick={() => {this.props.history.push({
  pathname: "/set_account",
  state: {userCell: userCell}
})}} />

Link와 같이

console.log(this.props.location.state.userCell)

props에 접근 할 수 있다.

+참고
https://velog.io/@dhlee91/this.props.history.push%EB%A1%9C-props-%EB%84%98%EA%B2%A8%EC%A3%BC%EA%B8%B0

profile
비전공 프론트엔드 개발자의 개발일기😈 ✍️

5개의 댓글

comment-user-thumbnail
2021년 11월 23일

history.push로 다음 페이지에 State를 넘길수 있다는 것이죠?
state: {userCell: userCell}
위 정의는 어떻게 읽으면될까요?

1개의 답글