프레임워크/React
React HoC 개념과 간단 사용방법
D.Y
2020. 1. 11. 00:44
React HoC(Higher-order Component)란?
- 리액트 컴포넌트를 인자로 받아서 다른 리액트 컴포넌트를 반환하는 함수를 고차함수라고 한다.
- 조금 더 자세히 설명하면, HoC의 원리는 파라미터로 컴포넌트를 받고, 함수 내부에서 새 컴포넌트를 만든 다음에 해당 컴포넌트 안에서 파라미터로 받아온 컴포넌트를 렌더링 하는 것이다.
React HoC는 언제 사용할까?
- 리액트 컴포넌트를 작성하게 될 때 반복될 수 있는 코드들을 HoC를 만들어서 해결할 수 있다.
코드
- 예를들어, 중복되는 HTTP 요청 코드가 존재할때 HoC를 사용하여 중복되는 코드를 제거할 수 있다.
- Github에 전체코드를 확인해보세요.
NewPost.tsx
import React from 'react';
import withRequest from "../components/withRequest";
interface PostIProps
{
data: string;
};
class Post extends React.Component< PostIProps >
{
public render(): JSX.Element
{
const {data} = this.props;
return (
< div >
{JSON.stringify(data)}
< /div >
)
}
}
export default withRequest('https://jsonplaceholder.typicode.com/posts/1')(Post);
NewComments.tsx
import React from 'react';
import withRequest from "../components/withRequest";
interface CommentsIProps
{
data: string;
};
class Comments extends React.Component< CommentsIProps >
{
public render(): JSX.Element
{
const {data} = this.props;
return (
< div >
{JSON.stringify(data)}
< /div >
)
}
}
export default withRequest('https://jsonplaceholder.typicode.com/comments?postId=1')(Comments);
withRequest.tsx - HTTP Request를 대신할 HoC, 고차함수
import React from 'react';
import axios from 'axios';
const withRequest = (url: string) => (WrappedComponent: React.ComponentType< any >) =>
{
return class extends React.Component
{
public state =
{
data: null
};
public componentDidMount(): void
{
this.initialize();
}
private async initialize()
{
try
{
const response = await axios.get(url);
this.setState({
data: response.data
});
}
catch (error)
{
console.log(error);
}
}
public render(): JSX.Element
{
const {data} = this.state;
if (!data)
return < div >로딩중< /div >;
return < WrappedComponent {...this.props} data={data} / >;
}
}
};
export default withRequest;
App.tsx - Component를 화면에 보여줄 Container Component
import React from 'react';
import './App.css';
import NewPost from "./pages/NewPost";
import NewComments from "./pages/NewComments";
class App extends React.Component
{
public render(): JSX.Element
{
return (
< div >
Post
< br / >
< NewPost />
< hr/ >
Comments
< br />< br />
< NewComments / >
< /div >
)
}
}
export default App;