react --state와 생명주기

오미희·2021년 7월 20일
0

react

목록 보기
5/15
//기본적 코드
<script type="text/babel">
class Clock extends React.Component{
    constructor(props){
        super(props);
       this.state = {date: new Date()}
    }
    // babel을 설정했으므로 위의 코드는 아래와 같이 짜는 것도 가능
    /*
    state = {
        date:new Date()
    }
    */
    render(){
        return(
            <div>
                <h3>hello world</h3>
                <h4>
                    It is
                    {this.state.date.toLocaleTimeString()}    
                </h4>
            </div>
        )
    }
}

ReactDOM.render(
    <Clock/>,
    document.querySelector('#root')
)

</script>

[출력물]

//클래스에 생명주기 메서드 추가
<script type="text/babel">
    class Clock extends React.Component{
        constructor(props){
            super(props)
            this.state = {date:new Date()}
        }
        // constructor()내에서는 가능한 setState()를 사용하지 않는다.
        // setState는 컴포넌트를 렌더링 함.
        /*
        constructor(props){
        super(props)
        this.state = {date:new Date()}
        }
        // 위의 코드는 babel 사용을 통해 
        그냥
        this.state={date:new Date()}로 가능
        */

        componentDidMount() 
        // componentDidMount() 최초 렌더링 직후 바로 실행되어 한 번만 실행 후 그 이후 렌더링시에는 실행되지 않음
        // 일반적으로 
            this.timerID = setInterval(
            // 일정한 시간 간격으로 해당 함수를 실행 
                ()=>this.tick(),1000
            )
        }
        // ** setTimeout() => 일정한 시간 후에 작업을 한 번 수행

        componentWillUnmount(){
        // componentWillunmount() -> 컴포넌트 제거
            clearInterval(this.timerID)
            // clearInterval() / clearTimeout() -> 지정된 작업을 수행 후 다음 작업 스케쥴을 중지, 실행중이던 작업을 중지하던 것은 아니다.
        }
        tick(){
            this.setState({
            // componentDidMount()가 한 번 실행된 후에 setState가 실행됨

                date:new Date()
            })
        }
        
        render(){
            return(
                <div>
                    <h1>hello world</h1>
                    <h2>it is{this.state.date.toLocaleTimeString()}</h2>
                </div>
            )
        }
    }

    ReactDOM.render(
        <Clock/>,
        document.getElementById('root')
    )   
    
    </script>

profile
안녕하세요

0개의 댓글