본문 바로가기
IT/React

React - 라우팅 #2 (예제 일부)

by 최고영회 2019. 5. 15.
728x90
반응형
SMALL

방문 기록을 가로채서 라우터가 브라우저의 주소 변경에 따라 적절한 컴포넌트를 렌더링하도록 해보자.

일반적인 <a href=""></a> 태그 대신 Router 컴포넌트가 처리할 링크를 history 라이브러리를 이용해 생성해 보자. 

import createHistory from 'history/createBrowserHistory';
cons history = createHistory();
const navigatoe = to => history.push(to);
export { history, navigate };

index.js 파일에 라우트를 설정하는 예제 코드

import React from 'react';
import { render } from 'react-dom';

import App from './pages/App';
import Home from './pages/Home';
import SinglePost from './pages/post';
import Login from './pages/login';
import NotFound from './pages/error/notfound';
import Router from './components/router/Router';
import Route from './components/router/Route';
import { history } from './history';  // 위에서 작성한 history

import './shared/carsh';
import './shared'service-worker';
import './shared'vendor';
import './style/styles.scss';

export const renderApp = (state, callback = () => {}) => {
  render(
    <Router {...state}>
      <Route path="" component={App}>
        <Route path="/" component={Home} />
        <Route path="/posts:postId" component={SinglePost} />
        <Route path="/login" component={Login} />
        <Route path="*" component={NotFound} />
      </Route>
    </Router>,
    document.getElementById('app'),
    callback
  );
};

// 경로와 사용자를 추적할 상태 객체 
let state = {
  location: window.location.pathname, 
  user: {
    authenticated: false,
    profilePicture: null,
    id: null,
    name: null,
    token: null
  }
};

// 경로가 변경되면 라우터를 갱신하기 위해 호출된다. 이때 어플리케이션은 새로운 상태 데이터와 함께 다시 렌더링 된다. 
history.listen(location => {
  const user = firebase.auth().currentUser;
  state = Object.assign({}, state, {
    location: user ? location.pathname : '/login'
  });
  renderApp(state);
})

renderApp(state); // 앱을 랜더링한다. 
728x90
반응형
LIST

'IT > React' 카테고리의 다른 글

React - 라우팅  (0) 2019.04.19
React - 폼 이벤트 핸들러, controlled component, uncontrolled component  (0) 2019.03.28
React - 에러처리  (0) 2019.03.27
React - 생명주기 메서드  (0) 2019.03.27
React - 컴포넌트 간의 통신  (0) 2019.03.15