TODO App 5. Comment 만들기

CommentForm만 만들고 미뤄놨던 Comment를 만들어보자.

Comment 작성

var React = require('react'),
    CommentStore = require('../stores/comment-store');

function getStateFromStore(){
  return {
    comments: CommentStore.getAll()
  };
}


var Comments = React.createClass({
  onChange: function(){
    this.setState(getStateFromStore())
  },

  getInitialState: function(){
    return getStateFromStore();
  },

  componentDidMount: function() {
    CommentStore.addChangeListener(this.onChange);
  },

  componentWillUnmount: function() {
    CommentStore.removeChangeListener(this.onChange);
  },

  render: function() {
    var comments = this.state.comments.map(function(comment, index){
      return (
          <div className='comment' key={'comment-' + index}>
            {comment.text}
          </div>
      );
    });

    return (
        <div className='comments'>
          {comments}
        </div>
    );
  }
});

module.exports = Comments;

코드를 천천히 리뷰해보자.

function getStateFromStore(){
  return {
    comments: CommentStore.getAll()
  };
}

위 함수는 Store로 부터 Comment Data를 가져와서 리턴해주는 메서드 인데 Store의 실제 Data는 감춰져 있고 getAll라는 Pubilc 메서드를 이용하여 가져올 수 있음을 알 수 있다.

그리고 Comment Component를 만들자.

onChange: function(){
    this.setState(getStateFromStore())
  },

  getInitialState: function(){
    return getStateFromStore();
  },

  componentDidMount: function() {
    CommentStore.addChangeListener(this.onChange);
  },

  componentWillUnmount: function() {
    CommentStore.removeChangeListener(this.onChange);
  }

하나씩 천천히 보자.

getInitialState,componentDidMount,componentWillUnmount 메서드는 React의 라이프사이클 메소드이다.

getInitialState에서 getStateFromStore 함수를 호출하여 Store에 있는 TODO 데이터를 가져온다.

componentDidMount 메서드는 CommentStore에 Change Event를 등록하고 인자로는 onChange 메서드를 준다.

우리가 위에서 작성한 CommentStore를 보면 addChangeListener에 등록한 Callback이 실행되는 시점은 Action으로 부터 데이터를 받아서 Store의 클로저로 접근되는 comment 변수에 데이터를 넣고 실행된다.

Callback으로 onChange 메서드를 넣어줬는데 onChange는 Store에서 데이터를 가져와 새로 그려주는 메서드이니 TODO를 추가할때마다 자동으로 그려주는 로직이라고 할 수 있다.

componentWillUnmount는 해당 Component가 사라질때 Store에 등록된 이벤트를 해제하는 역할을 한다.

그리고 onChange 메서드는 Data가 Change될때 해당 Compoent에 Data를 다시 Setting 해주는 역할을 한다.

이렇게하면 기본적인 View-Controller의 작성은 끝난다.