기본 콘텐츠로 건너뛰기

vulcanJS - 9. Route 연결하기

Route들끼리 연결에 대해 알아보자고 지난 시간에 말씀드렸는데
Vulcan에선 React-router(https://reacttraining.com/react-router/web/api/Link)를 사용하므로 그 규칙을 그대로 따르면 됩니다.
<Link to='경로명'>표시할 이름</Link> 형식으로 씁니다.
PostsSingleComponent 에 <Link to='/'>to Home</Link> 를 추가하여 처음으로 돌아가도록 합시다.
import React, { Component } from 'react';
import { Link } from 'react-router';
import { registerComponent, withDocument } from 'meteor/vulcan:core';
import Posts from "../modules/posts/collection.js";
class PostsSingleComponent extends Component {
  render () {
    return (
      <div>
        <h1>{this.props.document.title}</h1>
        <pre>
          {this.props.document.body}
        </pre>
        <Link to='/'>to Home</Link>
      </div>
    );
  }
}
registerComponent('PostsSingleComponent', PostsSingleComponent, [withDocument, {
  collection: Posts
}]);
export default PostsSingleComponent;
평범합니다. 이제 본문 글 목록에서도 상세로 들어올 수 있도록 제목마다 연결해 봅니다.
PostsListComponent에서 <div key={o._id}>{o.title}</div> 이 부분에 <Link>를 적용하면 아래와 같습니다.
import React, { Component } from 'react';
import { Link } from 'react-router';
import { registerComponent, withList } from 'meteor/vulcan:core';
import Posts from "../modules/posts/collection.js";
class PostsListComponent extends Component {
  render () {
    return (
      <div>
        {
          this.props.results
            && this.props.results.map(o=>
              <div key={o._id}>
                <Link to={`/posts/${o._id}`}>{o.title}</Link>
              </div>
            )
        }
      </div>
    );
  }
}
registerComponent('PostsListComponent', PostsListComponent, [withList, {
  collection: Posts
}]);
export default PostsListComponent;
o._id를 문자열 안에 넣기 위해 `(backtick)을 사용했습니다.
<Link to={`/posts/${o._id}`}>{o.title}</Link> 이렇게 접근하는 것이지요.

근데, 실제로 목록에서 상세로 연결하려고 눌러보면 생각대로 한번에 잘 들어가지지 않습니다.
어떻게 된 일 일까요?
콘솔 창에서 보면
PostsSingleComponent.jsx:11 Uncaught TypeError: Cannot read property 'title' of undefined
위와 같은 오류가 납니다.
즉 원인은 PostsListComponent가 아니라 PostsSingleComponent를 렌더링하는 시점에 this.props에 document라는 속성이 생기지 않았고 그 상태에서 document.title에 접근하고자 하였기 때문입니다.
Swift나 Coffeescript 같은 곳엔 optional 혹은 existential operator라고 불리는 연산자가 있어서 해당 속성 뒤에 ?를 써놓으면 미리 존재여부를 검사할 수 있는데 현재 ECMA6/7에선 지원하지 않습니다.
그렇다면 withDocument로부터 데이터가 다 불러졌는지 알려면 어떻게 해야할까요?
http://docs.vulcanjs.org/data-loading.html#withDocument를 보면 Document말고 loading이라는 속성이 있습니다. 로딩 여부를 반환하는 속성입니다. 이것을 이용합니다.
보통 로딩 시에 로딩 에니메이션을 화면에 보여주는데 화면이 번쩍하는게 싫으니 그냥 빈  <div />를 잠시 노출하도록 합니다.
import React, { Component } from 'react';
import { Link } from 'react-router';
import { registerComponent, withDocument } from 'meteor/vulcan:core';
import Posts from "../modules/posts/collection.js";
class PostsSingleComponent extends Component {
  render () {
    return (
      this.props.loading &&
      <div />
      ||
      <div>
          <h1>{this.props.document.title}</h1>
          <pre>
            {this.props.document.body}
          </pre>
          <Link to='/'>to Home</Link>
      </div>
    );
  }
}
registerComponent('PostsSingleComponent', PostsSingleComponent, [withDocument, {
  collection: Posts
}]);
export default PostsSingleComponent;
더 이상 오류가 발생하지 않습니다.
비동기 상황은 꼼꼼하게 점검해서 오류를 막아주도록 합시다.
다음은 수정과 삭제에 대해 알아보록 하겠습니다.

댓글

이 블로그의 인기 게시물

cURL로 cookie를 다루는 법

http://stackoverflow.com/questions/22252226/passport-local-strategy-and-curl 레거시 소스를 보다보면 인증 관련해서 cookie를 사용하는 경우가 있는데 가령 REST 서버인 경우 curl -H "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" 이렇게 로그인이 성공이 했더라도 curl -H "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이런 식으로 했을 때 쿠키를 사용한다면 당연히 인증 오류가 날 것이다. curl의 --cookie-jar 와 --cookie 옵션을 사용해서 cookie를 저장하고 꺼내쓰자. 각각 옵션 뒤엔 저장하고 꺼내쓸 파일이름을 임의로 지정하면 된다. 위의 과정을 다시 수정해서 적용하면 curl -H --cookie-jar jarfile "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" curl -H --cookie jarfile "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이렇게 사용하면

MQTT Broker Mosquitto 설치 후 설정

우분투 기준 $ sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa $ sudo apt-get update 하고 $ sudo apt-get install mosquitto 으로 설치하면 서비스까지 착실하게 올라간다. 설치는 간단한데 사용자를 만들어야한다. /etc/mosquitto/mosquitto.conf 파일에서 권한 설정을 변경하자. allow_anonymous false 를 추가해서 아무나 못들어오게 하자. $ service mosquitto restart 서비스를 재시작. 이제 사용자를 추가하자. mosquitto_passwd <암호파일 경로명> <사용자명> 하면 쉽게 만들 수 있다. # mosquitto_passwd /etc/mosquitto/passwd admin Password:  Reenter password:  암호 넣어준다. 두번 넣어준다. 이제 MQTT 약을 열심히 팔아서 Broker 사글세방 임대업을 하자.

OS X 터미널에서 tmux 사용시 pane 크기 조절

http://superuser.com/a/660072  글 참조. OS X 에서 tmux 사용시 나눠놓은 pane 크기 조정할 때 원래는 ctrl+b, ctrl+↑←→↓ 로 사이즈를 조정하는데 기본 터미널 키 입력이 조금 문제가 있다. 키 매핑을 다시 하자 Preferences(cmd+,) > Profile >  변경하고자 하는 Theme 선택 > Keyboards 로 들어가서 \033[1;5A \033[1;5B \033[1;5C \033[1;5D 를 순서대로 ↑↓→←순으로 매핑이 되도록 하면 된다. +를 누르고 Key에 해당 화살표키와 Modifier에 ctrl 선택 한 후 <esc>, [, 1, ;, 5 까지 한키 한키 입력 후 A,B,C,D를 써준다. 잘못 입력했을 땐 당황하지 말고 Delete on character 버튼을 눌러 수정하도록 하자. 그리고 다시 tmux에서 ctrl+b, ctrl+↑←→↓로 사이즈를 조절해보자. 잘 된다.