본문 바로가기
인강\개인공부/노마드 코더

[리액트] Component State &Life cycle -노마드코더

by 꼬바리 2021. 5. 3.

안녕하세요 꼬바리입니다.

public -> index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>

  </body>
</html>

 

 

 

src 폴더에 index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />,document.getElementById('root'));
//  <App /> ->componant는 HTML 을 반환하는 함수

 

 

 

src폴더에 App.js

import React from 'react';
import PropTypes from 'prop-types';


class App extends React.Component{
  constructor(props){
    super(props);
    console.log("hello");
  }
    state={
        count : 0
      }; 
    add = ()=>{
      this.setState(current =>({count:current.count+1}));
    };
    minus = ()=>{
      this.setState(current =>({count:current.count-1}));
     // this.setState({count:this.state.count-1});
     //위에 코드를 current 로 변경 가능 
    };
    componentDidMount(){
      console.log("component rendered");
      //컴포넌트가 render될때 
    }
    componentDidUpdate(){
      console.log("i just update");
      //먼저 render를 호출한 다음에 업데이트가 완료 되었다고 말하는 실행
    }
    componentWillUnmount(){
      console.log("goodbye ,  cruel world");
      //컴포넌트를 떠날 때 실행됨
      //어떤걸 하거나 다른 페이지로 갈때 
    }
    render(){
      console.log("i'm randering");
      return (
      <div>
        <h1>the number is :{this.state.count}</h1>
        <button onClick={this.add}>Add</button>
        <button onClick={this.minus}>Minus</button>
      </div>
      );
    }
}

export default App;

 

 

작성후 결과물

 

 

 

 

728x90

댓글