• 여러개의 Router를 생성하게 될텐데, 이렇게 되면 유지보수가 이후에는 어려워질수 있으니 router 모듈화를 진행
  • src/api/index.js 에 api에 관련된 호출을 나열

src/index.js

const Koa = require('koa');
const Router = require('koa-router');

const api = require('./api');

const app = new Koa();
const router = new Router();

// 라우터 설정
router.use('/api', api.routes()); // add api router

// app instance에 라우터 적용
app.use(router.routes()).use(router.allowedMethods());

app.listen(4000, () => {
  console.log('Listening to port 4000');
});

src/api/index.js

const Router = require('koa-router');
const api = new Router();

api.get('/test', ctx => {
  ctx.body = 'test 성공';
});

module.exports = api;
  • src/api/index.js를 생성하고, src/index.jsrouter.use를 통해 router를 등록해주면 된다.
  • 이때 주의해야할점은 src/api/index.js에서 반드시 exports를 해줘야 한다.

posts API 생성하기

  • src/api/posts/index.js에 아래와 같이 posts에 관련된 api의 목록들을 정의한다.
  • 정의한 route를 src/api/index.js에 적용을 해주면 된다.

src/api/index.js

const Router = require('koa-router');
const posts = require('./posts');

const api = new Router();

api.use('/posts', posts.routes());

module.exports = api;

src/api/posts/index.js

const Router = require('koa-router');
const posts = new Router();

const printInfo = ctx => {
  ctx.body = {
    method: ctx.method,
    path: ctx.path,
    params: ctx.params,
  };
};

posts.get('/', printInfo);
posts.post('/', printInfo);
posts.get('/:id', printInfo);
posts.delete('/:id', printInfo);
posts.put('/:id', printInfo);
posts.patch('/:id', printInfo);

module.exports = posts;
  • 위 같이 정의하고 http://localhost:4000/api/posts/12을 호출하면 아래와 같은 결과가 나온다.

  • withRouter 함수는 Higher-order Component
  • 라우터에 의해서 호출된 컴포넌트가 아니어도 match, location, history 객체에 접근할 수 있도록 해준다.

    참고로 history 는 match, location과 함께 전달되는 properties 중 하나로 페이지 이탈 방지할때 사용

import React from 'react';
import { withRouter } from 'react-router-dom';

const withRouterSample = ({ location, match, history }) => {
  return (
    <div>
      <h4>location</h4>
      <textarea
        value={JSON.stringify(location, null, 2)}
        rows={7}
        readOnly={true}></textarea>
      <h4>match</h4>
      <textarea
        value={JSON.stringify(match, null, 2)}
        rows={7}
        readOnly={true}></textarea>
      <button onClick={() => history.push('/')}>HOME</button>
    </div>
  );
};

export default withRouter(withRouterSample); 
  • 라우팅을 하는 컴포넌트가 있고, 그 라우팅된 컴포넌트에서 다른 컴포넌트를 사용할때 사용하면 된다.
  • 예를들면 도시의 목록이 있고, 그 도시 목록을 눌렀을때 아래 다른 컴포넌트가 표시될 필요가 있을때!
  • 검색된 결과를 받았을때 그 결과로 화면에 뿌려줘야 하는데 다른 컴포넌트에서도 쿼리가 필요할때

Routing 이란?

routing 은 특정 주소에 특정 페이지를 보여주는게 라우팅(Routing)

react-router 사용하기

default로 react는 routing의 기능이 없기 때문에 라우팅 라이브러리를 사용해야 한다. 가장 많이 사용하는 routing library는 react-router

yarn add react-router-dom

프로젝트에 라우터를 적용

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

위 코드에서 아래와 같이 추가

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <BrowserRouter>
    <App />{' '}
  </BrowserRouter>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

두개의 컴포넌트 생성하기

import React from 'react';

const Search = () => {
  return (
    <div>
      <h1>Search</h1>
    </div>
  );
};
export default Search;

import React from 'react';

const Home = () => {
  return (
    <div>
      <h1>Home</h1>
    </div>
  );
}; 
export default Home;

App.js 를 수정

  • app에서 exact={true}를 사용하지 않으면 search로 검색했을때 Home, Search의 두개의 페이지가 화면에 중복으로 표시된다.
  • Link를 클릭하면 다른 주소로 이동시켜주는 컴포넌트
  • a tag 를 사용하면 화면이 새로고침 된다. (페이지를 렌더링)
  • Link 사용하면 페이지 새로고침 하지 않고
import React from 'react';
import { Route, Link } from 'react-router-dom';
import './App.css';

import Home from './components/Home';
import Search from './components/Search';

const App = () => {
  return (
    <div>
      <Link to="/">홈</Link>
      <Link to="/search">검색</Link>
      <Route path="/" component={Home} exact={true}></Route>
      <Route path="/search" component={Search}></Route>
    </div>
  );
};

export default App;

웹 초보인 나로서는 화면과 화면 이동, 그리고 화면의 전환 등 Routing에 대한 어려움이 있다. 텍스트를 눌러서 다른 페이지로 이동하거나 메뉴를 만들어서 메뉴를 클릭하면 다른 페이지를 이동하거나... 별거 아닌것 같은데 눌렀을때 404 뜨거나 하면 그만큼 열불나는게 없다! 이해하려고 하는 시간이 필요함에도 우리는 이해하지 않고 그냥... 꾸역꾸역 하나씩 찍기를 시작하지.. 그래서 좋은 사이트!!! 

https://reacttraining.com/react-router/web/example/auth-workflow

 

React Router: Declarative Routing for React

Learn once, Route Anywhere

reacttraining.com

Reacttraining.com에 들어가서 react-router에 대해서 튜토리얼이 정리가 아~주 잘되어있다. 로그인을 했을때 nested, redicrect, Route config 등등 10가지 정도 넘게 방법론에 대해서 코드와 함께 제공되고 있다. 코드도 샌드박스로 제공하고 있어서 코드와 화면을 바로바로 수정해가면서 볼 수 있으니 ... 이건 뭐 거저 주는 느낌? BasicURL ParametersNestingRedirects (Auth)Custom LinkPreventing TransitionsNo Match (404)Recursive PathsSidebarAnimated TransitionsRoute ConfigModal GalleryStaticRouter ContextQuery Parameters

 

이렇게 예제들을 보면서 코드를 구성해보자~ 일단 무작정 만드는게 좋다. 백날 이해하려고 글을 읽어도... 글만 읽게 되니까! router에 대한 이해는 reacttraining에서 해야지!

'우리는 개발자 > Web' 카테고리의 다른 글

Web UI 개발할때는 storybook을 이용해보자  (0) 2019.12.20
React 를 시작하다.  (0) 2019.12.20

+ Recent posts