React Design Pattern

React를 작성할 때 기능과 출력을 같이 두는건 관리상 좋지 않기때문에 나눠서 작성하는 디자인 패턴이 있다.
Container - Presenter 패턴이라고 한다

일반적인 React 코드
import React, { Component } from "react";

class Blog extends Component {
    state = { loading: true };
    componentDidMount() {
        fetch("/api/blog")
        .then(res => res.json())
        .then(
            posts =>
                this.setState({
                    loading: false,
                    posts
                }),
            error => this.setState({ loading: false, error })
        );
    }
    render(){
        if(this.state.loading){
            return <div>Loading...</div>;
        } else {
            this.state.posts.map(post => <div key={post.id}>{post.title}</div>);
        }
    }
}
export default Blog;
이렇게 api기능과 출력이 한 코드내에 들어가 있는 것을
import React, { Component } from "react";
import Blog from './Blog';

class BlogContainer extends Component {
    state = { loading: true };    componentDidMount() {
        fetch("/api/blog")
        .then(res => res.json())
        .then(
            posts =>
                this.setState({
                    loading: false,
                    posts
                }),
            error => this.setState({ loading: false, error })
        );
    }
    render(){
        <Blog {...this.state} />;
    }
}
export default BlogContainer;
컨테이너는 다음과 같이 기능들만을 가지고 있다.

반면 프리젠터는
import React, { Component } from "react";

class Blog extends Component {
    _renderLoading = () => {
        return <div>Loading...</div>;
    };
    _renderError = () => {
        return <div>Error...</div>;
    };
    _renderPosts = () => {
        const { posts } = this.props;
        return posts.map(post => <div key={post.id}>{post.title}</div>);    };
    render(){
        if(this.props.loading){
            return this._renderLoading();
        } else if(this.props.posts){
            return this._renderPosts();   
        } else {
            return this._renderError();
        }
    }
}
export default Blog;
이렇게 UI에 관련된 출력기능만을 가지고 있다.

컨테이너 : state 변경, 리덕스 액션 호출, 액션 디스패치 ...
프리젠터 : 전달받은 props를 어떻게 출력할지 알려줌

댓글