React

13. React 라우팅

하늘을난모기 2018. 12. 2. 18:24

13. React 라우팅

React는 싱글페이지다. 즉, 앱을 사용하는 과정에서 URL의 변경이 거의 없다.

브라우저 렌더링 덕분에 서버에 연결할 이유가 없어서이다.

[ 문제점 ]

  • 브라우저를 새로고침 하면 읽고 잇던 페이지의 원래 폼으로 돌아간다.
  • 브라우저의 기록 기능은 접속해 잇던 사이틔의 단일 URL만 기록하므로 브라우저의 뒤로가기 버튼을 눌렀을 때
    완전히 다른 사이트로 이동할 수 있다. 페이지의 내용을 변경하면서 URL은 변경되지 않았기 때문이다.
  • 친구들에게 사이트의 특정 페이지를 공유할 수 없다.
  • 첫 페이지와 URL을 구분할 수 없으므로 검색 엔진이 사이트를 색인할 수 없다.

13.1 라우터를 처음부터 구현하기

  1. 입력된 URL에 따라 맵핑하기
  2. 라우터로 재사용성 높이기
  3. 라우터와 매핑으로 앱 구현

13.1.1 프로젝트 설정

13.1.2 app.jsx에서 경로 맵핑 설정

ex) 맵핑 설정 예제

const React = require('react')
const ReactDOM = requice('react-dom')
const Router = require('./router.jsx')
const mapping = {
    '#profile': <div>Profile (<a href="#">home</a>)</div>,
    '#accounts': <div>Accounts (<a href="#">home</a>)</div>,
    '*': <div>Dashboard<br/>
        <a href="#profile">Profile</a>
        <br/>
        <a href="#accounts">Accounts</a>
        </div>
}

ReactDOM.render(
    <Router mapping={mapping}/>,
    document.getElementById('content')
)

13.1.3 router.jsx 파일에 Router 컴포넌트 생성하기

ex) router.jsx 파일 예제

const React = require('react')
module.exports = class Router extends React.Component {
    constructor(props) {
        super(props)
        this.state = {hash: window.location.hash}
        this.updateHash = this.updateHash.bind(this)
    }
    render() {
        ...
    }
}

ex) hashchange 이벤트 예시 (URL 변경 감지)

updateHash(event) {
    this.setState({hash: window.location.hash})
}
componentDidMount() {
    window.addEventListener('hashchange', this.updateHash, false)
}
componentWillUnmount() {
    window.removeEventListener('hashchange', this.updateHash, false)
}

13.2 React Router

ex) Router 예시

<Router>
    <Route path="/" component={Content} >
        <Route path="/about" component={About} />
            <Route path="/about/company" component={AboutCompany} />
            <Route path="/about/author" component={AboutAuthor} />
        <Route path="/posts" component={Posts} />
        <Route path="/posts/:id component={Post} />
        <Route path="/contact" component={Contact} />
    </Route>
</Router>

13.2.1 JSX로 React Router 사용하기

13.2.2 해시 히스토리

13.2.3 브라우저 히스토리

브라우저 히스토리 URL은 실제 URL임.

URL 요청 시 서버 요청으로 이어짐.

13.2.4 React Router를 사용하기 위한 Webpack 설정

13.2.5 레이아웃 컴포넌트 생성하기

13.3 React Router의 기능과 패턴

13.3.1 withRouter 고차 컴포넌트를 이용해서 라우터 접근하기

ex) withRouter 사용 에제

const {withRouter} = require('react-router')
...
<Router ...>
    ...
    <Route path="/contact" component={withRouter(Contact)} />
</Router>

--------

const React = require('react')
module.exports = function Contact(props) {
    return <div> ... </div>
}

withRouter는 일반적인 상태저장 React 컴포넌트는 물론 상태비저장 컴포넌트에서도 사용할 수 있다.

13.3.2 프로그래밍적으로 페이지 이동하기

router.push(URL)

ex) 1초 뒤 페이지 이동하는 예제

const React = require('react')

module.exports = function Contract(props) {
    setTimeout(() => {props.router.push('about')}, 1000)
    return <div>
        <h3>Contact us</h3>
        <input type="text" placeholder="email" className="form-control" />
        <textarea type="text" placeholder="message" className="form-control" />
        <button className="btn btn-primary">send</button>
    </div>
}

13.3.3 URL 매개변수와 데이터 전달

ex) 예제

const React = require('react')

module.exports = function Product(props) {
    let post = props.route.posts.find(element=>element.slug == props.params.id)
    return (
        <div>
            <h3>{post.title}</h3>
            <p>{post.text}</p>
            <p><a href={post.link} target="_blank">Continue reading...</a></p>
        </div>
    )
}

13.3.4 React Router에서 속성 전달하기

13.4 Backbone을 이용한 라우팅

요약

  • hashchange 이벤트를 이용하면 React를 이용한 단순한 라우팅을 구현할 수 있다.
  • React Router는 라우팅 계층을 정의할 수 있는 JSX 문법을 제공한다:
  • Route 컴포넌트가 중첩되는 경우에 URL은 부모 Route와 중첩하지 않도록 할 수 있다. 즉, 경로와 중첩 여부는 독립적이다.
  • queeryKey를 false로 설정하면 토큰 없이 해시 히스토리를 사용할 수 있다.
  • JSX는 React.createElement()로 변환되어 React가 필요하므로 JSX에서 React를 직접 사용하지 않더라도 React를 불러와야 한다.(require('react'))