이번 포스팅에서는 State 끌어올리기에 대해 알아보고자 한다.
Component 구조로 이루어진 React에서는 종종 동일한 데이터에 대한 변경사항을 여러 component에 반영해야 할 필요가 있다. 이럴 때 사용하는 테크닉 중 하나가 가장 가까운 공통 조상으로 state를 끌어올리는 것이다. 전체적인 프로세스는 다음과 같다.
1. 가장 가까운 부모 component 안에서 state를 만들어준다.
2. 부모 component 안에서 state를 변경할 수 있는 함수를 만들어서 자식 component에게 전달한다.
3. 자식 component는 전달 받은 함수를 이용해서 부모 component의 state를 변경한다.
4. 상태가 변경되었기 때문에 자식 component 안의 render( ) 함수들이 다시 실행된다.

코드를 살펴보면서 좀 더 이해해보도록 하자.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>form</title> <script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> </head> <body> <div id="root"></div> <script type="text/babel"> class Form extends React.Component { handleChange = (e) => { const {target: {value}} = e this.props.change(value) } handleSubmit = (e) => { e.preventDefault() } render() { const { props: {value}, handleChange, handleSubmit } = this return ( <form onSubmit={handleSubmit}> 내용: <input type='text' value={value} onChange={handleChange} /> <input type='submit' value='확인' /> </form> ) } } class Value extends React.Component { render() { return( <h3>{this.props.value}</h3> ) } } class App extends React.Component { state = { value: '' } changeValue = v => { this.setState({ ...this.state, value: v }) } render() { return( <div> <Form change={this.changeValue} value={this.state.value} /> <Value value={this.state.value} /> </div> ) } } ReactDOM.render( <App />, document.querySelector('#root') ) </script> </body> </html>
현재 <App /> component 안에 <Form /> component와 <Value /> component가 존재하고 있는 상황이다. 그리고 <App /> component 안에는 value 속성을 가지고 있는 state와 state의 value 값을 변경할 수 있는 changeValue( ) 함수를 만들었다. <Form /> component에 change라는 변수명으로 changeValue( ) 함수를 전달하였고 state의 value 값을 value라는 변수명으로 전달하였다.
<Form /> component 안의 input 엘리먼트에 onChange 이벤트를 걸어줌으로써 onChange 이벤트가 발생할 때마다 <Form /> component 안에서 정의한 handleChange( ) 함수가 실행되도록 하였다. handleChange( ) 함수는 this.props.change( ) 함수를 실행시켜 <App /> component의 state를 변경시킨다. 부모 component인 <App /> 의 state가 변경되었기 때문에 <Form /> component와 <Value /> component의 render( ) 함수가 다시 실행되면서 변경된 value 값으로 화면이 다시 그려지게 된다.
( State 끌어올리기 시연 영상 )

'React' 카테고리의 다른 글
React - webpack.config.js (0) | 2022.04.20 |
---|---|
React - Webpack (0) | 2022.04.18 |
React - 리스트와 Key (0) | 2022.04.15 |
React - Props & State (0) | 2022.04.14 |
React 기본 개념 (0) | 2022.04.12 |