HOC

00_8_3·2020년 9월 20일
0

HOC

HOC란 High Order Components

코드를 작성하다 보면 자주 반복하는 코드들이 있다.
그러한것들을 함후화해서 재사용 하곤하는데

컴포넌트 또한 비슷하다

import React, { Component } from 'react';

const withRequest = (url) => (WrappedComponent) => {
  return class extends Component {
    render() {
      return (
        <WrappedComponent {...this.props}/>
      )
    }
  }
}

export default withRequest;

HOC 작성할 때 이름을 with_ 형식으로 짓는다.

파라미터로 컴포넌트를 받아오고 함수 내부에서 새 컴포넌트를 만든 다음에

해당 컴포넌트 안에서 파라미터로 받아온 컴포넌트를 렌더링 하는 것이다.

그리고 자신이 받아온 props들은 그대로 파라미터로 받아온 컴포넌트에게 다시 주입해주고

필요에 따라 추가 props도 넣어준다.

HOC를 작성해보자

withRequest.js

import React, { Component } from 'react';
import axios from 'axios';

const withRequest = (url) => (WrappedComponen) => {
  return class extends Component {

    state = {
      data: null
    }

    async initialize() {
      try {
        const response = await axios.get(url);
        this.setState({
          data: response.data
        });
      } catch (e) {
        console.log(e);
      }
    }

    componentDidMount() {
      this.initialize();
    }

    render() {
      const { data } = this.state;
      return (
        <WrappedComponent {...this.props} data={data}/>
      )
    }
  }
}

export default withRequest;

Post.js

import React, { Component } from 'react';
import withRequest from './withRequest';

class Post extends Component {
  render() {
    const { data } = this.props;
    
    if (!data) return null;

    return (
      <div>
        { JSON.stringify(this.props.data) }    
      </div>
    );
  }
}


export default withRequest('https://jsonplaceholder.typicode.com/posts/1')(Post);

컴포넌트 내보낼때 이렇게 사용한다.

출처 : https://velopert.com/3537
출처 : https://ko.reactjs.org/docs/higher-order-components.html
출처 : https://reactjs-kr.firebaseapp.com/docs/higher-order-components.html

0개의 댓글