13.2 서브 라우트 & 기능

hey hey·2021년 12월 13일
0

리액트 배우기

목록 보기
18/26

서브 라우트

라우트 내부에 또 라우트를 정의하는 것

Profiles.js

import {Link,Route} from 'react-router-dom'
import Profile from './Profile'

const Profiles = () =>{
  return (
    <div>
      <h3>사용자 목록</h3>
      <ul><Link to="/profiles/heyhey">현홍</Link></ul>
      <ul><Link to="/profiles/gildong">길동</Link></ul>
    
      <Route path="/profiles" exact
      render={()=><div>사용자를 선택해 주세요</div>}/>
      <Route path="/profiles/:username" component={Profile}/>
    </div>
  )
}
export default Profiles

<Route path="/profiles" exact render={()=><div>사용자를 선택해 주세요</div>}/>

  • component 대신 render라는 props를 넣어주었다.
  • 컴포넌트 자체를 전달하는 것이 아닌 보여주고 싶은 JSX를 넣어줄 수 있다.
  • 따로 컴포넌트를 만들기 애매하거나 , 컴포넌트에 props를 별도로 넣고 싶을 때 사용
  • exact 만 적어도 알아서 exact ={true} 라고 설정된다.

App.js

profile 지우고 profiles로 연결

<li><Link to='/profiles'>프로필</Link></li>
<Route path="/profiles" component={Profiles}/>

정리

  1. profiles 로 가는 Route를 만들고

    <Route path="/profiles" component={Profiles}/>

  2. Route 와 연결되는 Link도 만들어 준다

    <li><Link to='/profiles'>프로필</Link></li>

  3. Profiles.js 에서

    • path가 /profiles 뿐이라면: <Route path="/profiles" exact render={()=><div>사용자를 선택해 주세요</div>}/> Route와 같지만 component로 이동되는 것이 아닌 render()을 통해 보여주기만 한다.
    • path가 /profiles/이름 이 들어온다면 <Route path="/profiles/:username" component={Profile}/> Profile component로 이동한다
  4. Profile.js 에서

    • 데이터가 저장되어있고
    • 받아온 값에서 :username 의 위치를 찾는다
      • match.params에 있다
      • 이걸 data[username]으로 찾아서 저장하고
      • 그 값이 있으면 보여준다 .

라우터 부가 기능

history

정말 떠나실 건가요?

import React,{Component} from 'react'

class HistorySample extends Component{
  handleGoback = ()=>{
    this.props.history.goBack()
  }
  handleGoHome = ()=>{
    this.props.history.push('/')
  }
  componentDidMount(){
    this.unblock = this.props.history.block('정말 떠나시나요')
  }
  componentWillUnmount(){
    if (this.unblock){
      this.unblock()
    }
  }
  render(){
    return(
      <div>
        <button onClick={this.handleGoback}>뒤로</button>
        <button onClick={this.handleGoHome}></button>
      </div>
    )
  }
}
export default HistorySample

handleGoback = ()=>{this.props.history.goBack()} 뒤로가기
handleGoHome = ()=>{this.props.history.push('/')} ' / '(홈)으로 가기

componentDidMount(){this.unblock = this.props.history.block('정말 떠나시나요') }

  • 이것을 설정하고 나면 페이지ㅣ에 변화가 생길려고 할때 나갈 건지 질문한다.

    componentWillUnmount(){ if (this.unblock){this.unblock()}}

  • 컴포넌트가 언마운트되면 질문을 멈춘다.

withRouter

라우트로 사용된 컴포넌트가 아니어도 match, location, history 객체를 접근할 수 있게 한다.

  • 책 보기

Switch

여러 route를 감싸서 그중 일치하는 단 하나의 라우트만을 렌더링 시켜준다.

모든 규칙과 일치하지 않을 때 보여줄 Not Found페이지도 구현 가능하다

App.js

import { Route,Link,Switch} from 'react-router-dom';
<Switch>
  <Route path="/" component={Home} exact={true}/>
  <Route path="/about" component={About}/>
  <Route path="/profiles" component={Profiles}/>
  <Route path="/history" component={HistorySample}/>
  <Route render={({location})=>(
    <div>
      <h2>이 페이지는 존재 안합니다.</h2>
      <p>{location.pathname}</p>
    </div>
  )} />
</Switch>
  • 없는 페이지를 검색하게 되면 페이지가 존재하지 않는다는 글이 보인다.

NavLink

Link와 사용방법 비슷

현재 경로와 Link에서 사용하는 경로가 일치하는 경우 특정 스타일 적용가능

Profiles.js

import {NavLink,Route} from 'react-router-dom'
	const Profiles=()=>{
	const activeStyle ={
	    background:'white',
	    color:'black'
	  }
	<ul><NavLink activeStyle={activeStyle} to="/profiles/heyhey">현홍</NavLink></ul>
	<ul><NavLink activeStyle={activeStyle} to="/profiles/gildong">길동</NavLink></ul>
}
profile
FE - devp

0개의 댓글