본문 바로가기

React & Angularjs

부록. Container Components 와 Stateless Functional Components in React 0.14

요새 React 프로젝트 Refactoring 작업을 하고 있는데


주 미션은 아래와 같다.

"container 와 component 를 잘 구분하고, Reusable 한 컴포넌트는 반드시 reusable 할 수 있도록 하자"


그래서 오늘은 container component 패턴과 container 안에 포함되는 component를 짤 때 어떤 스타일로 짜면 좋을지 한번 포스팅 해보려 한다.




container, component 란?

만약 StockWidget 이라는 페이지가 있다면 그 페이지는 StockWidget 이라는 component 를 가질것이고, TagCloud 라는 페이지가 있다면 그 페이지는 TagCloud 라는 component 를 가질것이다. 즉, container 란 보통 페이지처럼 여러개의 component 를 가지고 있는 단위를 의미한다

StockWidgetContainer => StockWidget
TagCloudContainer => TagCloud
PartyPooperListContainer => PartyPooperList


그럼 여기서 생기는 의문점이 그럼 component 랑 container 를 나누는 기준은 뭔데??


라는 것에서 


CommentListContainer.js

class CommentListContainer extends React.Component {
  constructor() {
    super();
    this.state = { comments: [] }
  }
  componentDidMount() {
    $.ajax({
      url: "/my-comments.json",
      dataType: 'json',
      success: function(comments) {
        this.setState({comments: comments});
      }.bind(this)
    });
  }
  render() {
    return ;
  }
}

CommentList.js

class CommentList extends React.Component {
  constructor(props) {
    super(props);
  }
  render() { 
    return 
    {this.props.comments.map(renderComment)}
; } renderComment({body, author}) { return
  • {body}—{author}
  • ; } }


    위와 같이 component 는 state 를 가지지 않는다. 

    container 에서 data 를 fetching 하고, component 에서 이러한 data 를 prop 으로 받아 stateless 한 상태를 유지하고 state 가 바뀌어도 reusable 할 수 있는 상태로 유지한다.


    여기까지가 container component 패턴이고, stateless component 를 작성할 땐 다음과 같이 한다. ( React 0.14 부터 ㅎㅎ react 공식 홈페이지에서 아래와 같이 짜기를 권고한다. )

    const Text = (props) =>
      

    {props.children}

    ; // ReactDOM is part of the introduction of React 0.14 ReactDOM.render( Hello World, document.querySelector('#root') );





    참고 링크 

     - https://medium.com/@learnreact/container-components-c0e67432e005#.x5y2u4bd6


     - https://medium.com/@joshblack/stateless-components-in-react-0-14-f9798f8b992d#.zb9qopapz


     - https://facebook.github.io/react/blog/2015/09/10/react-v0.14-rc1.html#stateless-function-components