High-order Component (๊ณ ์ฐจ ์ปดํฌ๋ํธ)
Hoc
์ ๋ง๋ค์ด์ ํด๊ฒฐํ ์ ์๋ค.HOC
๋ ์ปดํฌ๋ํธ๋ฅผ ๊ฐ์ ธ์ ๊ธฐ๋ฅ์ ์ถ๊ฐํ์ฌ ์ ์ปดํฌ๋ํธ๋ฅผ ๋ฐํํ๋ ํจ์์ด๋ค.// Post.js
import React, { Component } from 'react';
import axios from 'axios';
class Post extends Component {
state = {
data: null
}
async initialize() {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
this.setState({
data: response.data
});
} catch (e) {
console.log(e);
}
}
componentDidMount() {
this.initialize();
}
render() {
const { data } = this.state;
if (!data) return null;
return (
<div>
{ JSON.stringify(data) }
</div>
);
}
}
export default Post;
// Comments.js
import React, { Component } from 'react';
import axios from 'axios';
class Comments extends Component {
state = {
data: null
}
async initialize() {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/comments?postId=1');
this.setState({
data: response.data
});
} catch (e) {
console.log(e);
}
}
componentDidMount() {
this.initialize();
}
render() {
const { data } = this.state;
if (!data) return null;
return (
<div>
{JSON.stringify(data)}
</div>
);
}
}
export default Comments;
HoC
์ ์์ฑํ๋ค.HoC
์ ์ด๋ฆ์ ๋ง๋ค ๋ with_
ํ์์ผ๋ก ์ง๋๋ค.๐ก ์ธ์๋ก ์ปดํฌ๋ํธ๋ฅผ ๋ฐ๊ณ , ์ ์ปดํฌ๋ํธ๋ฅผ ๋ฐํํ๋ค. ๋ฐํ๋ ์ปดํฌ๋ํธ ์์์ ์ธ์๋ก ๋ฐ์ ์ปดํฌ๋ํธ๋ฅผ ๋ ๋๋งํ๋ค. ์ด๋ ์ธ์๋ก ๋ฐ์ ์ปดํฌ๋ํธ์ ์๋
props
๋ค์ ๊ทธ๋๋ก ์ ๋ฌํ๊ณ , ํ์์ ๋ฐ๋ผ ์ถ๊ฐprops
๋ ๋ฃ์ด์ค๋ค.
โ Closure
๊ฐ๋
์ด ์ฌ์ฉ๋์๋ค. HoC์ด ์ข
๋ฃ๋์ด๋ ๋ฐํ๋ ์ปดํฌ๋ํธ๋ Hoc์ด ์ธ์๋ก ๋ฐ์ ์ปดํฌ๋ํธ๋ฅผ ๊ธฐ์ตํด์ผ ํ๋ค!
// withRequest.js
import React, { Component } from 'react';
const withRequest = (url) => (WrappedComponent) => {
return class extends Component {
state = {
data: null
}
async initialize(){
try{
const response = await axios.get(url); // 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}/> // WrapperComponent๋ฅผ ๊ธฐ์ตํด์ผ ํจ.
)
}
}
}
export default withRequest;
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);
import React, { Component } from 'react';
import withRequest from './withRequest';
class Comments extends Component {
render() {
const { data } = this.props;
if (!data) return null;
return (
<div>
{JSON.stringify(data)}
</div>
);
}
}
export default withRequest('https://jsonplaceholder.typicode.com/comments?postId=1')(Comments);
โ ๊ณ ์ฐจ ์ปดํฌ๋ํธ๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ด ๋ฆฌ๋์ค์
connet
ํจ์์ ๋งค์ฐ ์ ์ฌํ๋ค๊ณ ์๊ฐํ๋๋ฐ ๊ณต์ ๋ฌธ์๋ฅผ ์ฝ์ด๋ณด๋connect
ํจ์์์ ๊ณ ์ฐจ ์ปดํฌ๋ํธ๋ฅผ ์ด์ฉํ๋ค๊ณ ํ๋ค.