HOC(Higher-order Component)

BoeunSong·2021년 3월 11일
0

HoC란 자주 반복해서 작성하게 되는 코드를 함수화하여 재사용하는 것을 말합니다.

HOC 작성하기

HOC의 원리는 파라미터로 컴포넌트를 받아오고, 함수 내부에서 새 컴포넌트를 만든 다음에 해당 컴포넌트 안에서 파라미터로 받아온 컴포넌트를 렌더링 하는 것입니다. 그리고 자신이 받아온 props들은 그대로 파라미터로 받아온 컴포넌트에게 다시 주입해주고, 필요에 따라 추가 props도 넣어줍니다.

withRequest.js

import React, {Component} from 'react';

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

export default withRequest

HOC 에 기능 붙이기

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

const withRequest = (url) => (WrappedComponent) => {
	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}/>
            )
        }
    }
}

HOC 사용하기

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(url)(Post)


컴포넌트를 내보낼때 이렇게 사용하거나,

const PostWithData = withRequest(url)(Post)
export default PostWithData

이렇게 사용합니다.

출처: [링크텍스트](https://velopert.com/3537)
profile
매일 발전하는 프론트엔드 개발자🥰

0개의 댓글