티스토리 뷰
13. React 라우팅
React는 싱글페이지다. 즉, 앱을 사용하는 과정에서 URL의 변경이 거의 없다.
브라우저 렌더링 덕분에 서버에 연결할 이유가 없어서이다.
[ 문제점 ] * 브라우저를 새로고침 하면 읽고 잇던 페이지의 원래 폼으로 돌아간다. * 브라우저의 기록 기능은 접속해 잇던 사이틔의 단일 URL만 기록하므로 브라우저의 뒤로가기 버튼을 눌렀을 때 완전히 다른 사이트로 이동할 수 있다. 페이지의 내용을 변경하면서 URL은 변경되지 않았기 때문이다. * 친구들에게 사이트의 특정 페이지를 공유할 수 없다. * 첫 페이지와 URL을 구분할 수 없으므로 검색 엔진이 사이트를 색인할 수 없다.
13.1 라우터를 처음부터 구현하기
- 입력된 URL에 따라 맵핑하기
- 라우터로 재사용성 높이기
- 라우터와 매핑으로 앱 구현
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':
ReactDOM.render(
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')
...
const React = require('react') module.exports = function Contact(props) { return
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
Contact us
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 (
) } ```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'))
'React' 카테고리의 다른 글
MobX (0) | 2018.12.02 |
---|---|
13. React 라우팅 (0) | 2018.12.02 |
8. 확장성을 고려한 React 컴포넌트 (0) | 2018.12.02 |
7. React에서 폼 다루기 (0) | 2018.12.02 |
6. React에서 이벤트 다루기 (0) | 2018.12.02 |
5. React 컴포넌트 라이프사이클 이벤트 (0) | 2018.12.02 |
- Total
- 25,148
- Today
- 8
- Yesterday
- 36
- 안드로이드 툴바 마진 없애기
- letsencrypt오류
- moment 서울 시간 구하기
- javascript 한국 시간
- android toolbar margin-left
- java
- HashMap HashTable ConcurrentHashMap
- 툴바 왼쪽 마진
- Solidity Tutorial
- letsencrypt실패
- 안드로이드 툴바 마진
- 툴바 마진
- node.js 한국 시간
- REST vs SOAP
- letsencrypt등록
- 안드로이드 키보드 viisible
- 솔리디티
- moment 한국시간
- CBT
- ConcurrentHashMap
- node .js 한국시간 구하기
- toolbar margin left
- 안드로이드 키보드 확인
- letsencrypt
- moment 서울 시간
- 자바
- node.js 서울 시간 구하기
- 네이버 지도 마커
- 솔리디티 튜토리얼
- 2017 티스토리 결산