Frontend/React

React | ๋ Œ๋”๋ง ์ฃผ๊ธฐ - ์ƒ์„ฑ ๋‹จ๊ณ„ (Mounting)

์ด์ œํฌ 2023. 11. 30. 17:00


  •  counstructor()
    • ์ปดํฌ๋„ŒํŠธ ์ƒ์„ฑ ์‹œ ๊ฐ€์žฅ ๋จผ์ € ํ˜ธ์ถœ๋˜๋Š” ์ฒซ๋ฒˆ์งธ ๋ฉ”์„œ๋“œ
    • ์ดˆ๊ธฐ ์ƒํƒœ ์„ค์ • ๋ฐ ๋ฐ์ดํ„ฐ ๋ฐ”์ธ๋”ฉ์„ ์ˆ˜ํ–‰ํ•œ๋‹ค.
  • state getDerivedStateFromProps()
    • props๋กœ๋ถ€ํ„ฐ ์ƒํƒœ๋ฅผ ๋™๊ธฐํ™” ํ•˜๊ณ ์ž ํ•  ๋•Œ ํ˜ธ์ถœํ•˜๋Š” ๋ฉ”์„œ๋“œ
  • render()
    • ์ปดํฌ๋„ŒํŠธ UI ๋ Œ๋”๋ง์„ ์ˆ˜ํ–‰ํ•œ๋‹ค.
  • componentDidMount()
    • ์ƒ๋ช…์ฃผ๊ธฐ ๋ฉ”์„œ๋“œ ์ค‘ ํ•˜๋‚˜.
    • ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋ Œ๋”๋ง์ด ์™„๋ฃŒ ๋˜๊ณ  DOM์— ๋งˆ์šดํŠธ ๋˜๊ณ ๋‚œ ์ดํ›„์— ์‹คํ–‰๋˜๋Š” ๋ฉ”์„œ๋“œ
    • ์ดˆ๊ธฐ ๋ฐ์ดํ„ฐ ๋กœ๋”ฉ ํ˜น์€ ์™ธ๋ถ€ ๋ฐ์ดํ„ฐ ์š”์ฒญ ๋“ฑ์˜ ๋น„๋™๊ธฐ ์ž‘์—…์„ ์‹คํ–‰ํ•œ๋‹ค.

 

import React, { Component } from 'React'

class MyComponent extends Component {
    constructor(props) {
        super(props);
     	// ์ดˆ๊ธฐ ์ƒํƒœ ์„ค์ •
        this.state = { 
            count : 0,
        };
    }
    
    static getDerivedStateFromProps(nextProps, prevState) {
        // nextProps๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ์ƒํƒœ๋ฅผ ์—…๋ฐ์ดํŠธ
        if (nextProps.someValue !== prevState.someValue) {
            return {
            	someValue: nextProps.someValue,
            };
        }
        // ์ƒํƒœ๋ฅผ ์—…๋ฐ์ดํŠธํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค๋ฉด null์„ ๋ฐ˜ํ™˜
        return null;
    }
    
    render() {
        return (
            <div>
            	<p>{this.state.count}</p>
            </div>
        );
    }
    
    componentDidMount() {
        // ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋งˆ์šดํŠธ๋œ ํ›„์— ์‹คํ–‰
        console.log("Component is mounted!"); 
    }
}

export default MyComponent;
๋ฐ˜์‘ํ˜•