본 게시글은 구름EDU 처음 만난 React 온라인강의를 시청한 후 학습한 정보를 기록하는 목적의 게시글입니다.

생각의 흐름에 따라 작성된 게시글입니다. 가독성이 떨어질 수 있습니다.

처음 만난 React

 

처음 만난 React(리액트) - 구름EDU

굉장히 기초적인 내용 위주로 빠르고 쉽게 만나는 React! 웹 서비스를 위해 알아두어야 할 리액트 필수 개념을 짚어봅시다.

edu.goorm.io

구름 EDU

 

구름EDU - 모두를 위한 맞춤형 IT교육

구름EDU는 모두를 위한 맞춤형 IT교육 플랫폼입니다. 개인/학교/기업 및 기관 별 최적화된 IT교육 솔루션을 경험해보세요. 기초부터 실무 프로그래밍 교육, 전국 초중고/대학교 온라인 강의, 기업/

edu.goorm.io


 

React Component State?
= React Component Data
= Component에 대한 변경 가능한 Data
State는 사용자가 정의한다.
Rendering을 할 때, 사용되는 값들을 State에 포함
(그렇지 않은 경우는 정적인 data로 관리)

State란?
JavaScript의 객체; key & value 값
state는 직접 수정 할 수 없다. 보다 자세히 말하면 하면 안된다.
**set state function을 통하여 변경하여 수정 가능; setState({})**

Lifecycle?
Component Lifecycle.
Mounting -> Updating -> Unmounting


State

{Project Name} / src / App.js

import React from 'react';

import logo from './logo.svg';

import './App.css';

import Comment from './Comment'

 

const commentsFromServer = [

    {name : 'Jaewon Lee', content: '리엑트는 어려웡...'},

    {name : '부학회장', content: '그래도 열심히 해야지....'},

    {name : 'Ethan', content: '너희들은 열심히 하구 있니...?'},

];

 

var timer;

 

class App extends React.Component{

 

  constructor(props) {

    super(props);

 

    this.state = {

      comments : [],

    };

  }

 

  componentDidMount(){

    let comments = this.state.comments;

    timer = setInterval(() => {

      if(comments.length < commentsFromServer.length){

        let index = comments.length;

        comments.push(commentsFromServer[index]);

        //반드시 setState 함수를 사용할 것!

        this.setState({

          comments: comments

        });

      } else if (timer){

        clearInterval(timer);

      }

    }, 1000);

  }

 

  render(){

    const { comments } = this.state;

 

    return(

      <div className="App" style={{padding:16, backgroundColor:'#282c34'}}>

      <header className="App-header">

        <img src={logo} className="App-logo" alt="logo" />

        <p>

          Edit <code>src/App.js</code> and save to reload.

        </p>

        <a

          className="App-link"

          href="https://reactjs.org"

          target="_blank"

          rel="noopener noreferrer"

        >

          Learn React

        </a>

      </header>

      <div>

        {comments.map((comment, index) =>{

          return (

            <Comment

              name={comment.name}

              content={comment.content} />

          )

        })}

      </div>

    </div>

    );

  }

}

export default App;

{Project Name} / src / Comments.js

import React from 'react';

 

const styles ={

    root:{

        width:'20%',

        margin:'auto',

        marginTop: 16,

        padding: 16,

        textAlign: 'left',

        backgroundColor: 'white',

        borderRadius: 16,

    },

    imageContainer:{

        display: 'inline-block',

        width: '50',

    },

    image: {

        width: 50,

        height: 50,

        borderRadius: 25,

    },

    commentContainer: {

        display: 'inline-block',

        marginLeft: 16,

        textAlign: 'left',

        verticalAlgin: 'top',

    },

    nameText: {

        color : 'black',

        fontszie : 20,

        fontWeight: 700,

    },

    contentText: {

        color: 'black',

        fontszie: 16,

    }

}

 

class Comment extends React.Component{

    render() {

        const { name, content } = this.props;

 

        return(

            <div style={styles.root}>

                <div style={styles.imageContainer}>

                    <img

                        src='https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png'

                        style={styles.image} />

                </div>

                <div style={styles.commentContainer}>

                    <div style={styles.nameText}>

                        {name}

                    </div>

                    <span style={styles.contentText}>

                        {content}

                    </span>

                </div>

             </div>

        )

    }

}

 

export default Comment;

크롬개발자도구 활용하기

https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=ko&

 

React Developer Tools

Adds React debugging tools to the Chrome Developer Tools. Created from revision 75726fadfd on 10/19/2020.

chrome.google.com


LifeCycle

{Project Name} / src / Comment.js

class Comment extends React.Component{

 

    constructor(props){

        super(props);

    }

 

    componentDidMount(){

        

        console.log('%d componentDidMount() called.', this.props.id);

    }

 

    componentDidUpdate(){

        console.log('%d componentDidUpdate() called.', this.props.id);

    }

 

    componentWillUnmount(){

        console.log('%d componentWillUnMount() called.', this.props.id);

    }

    render() {

...

}

export default Comment;

{Project Name} / src / App.js

 componentDidMount(){

    let comments = this.state.comments;

    timer = setInterval(() => {

      //case#1 : 생성

      /*

      if(comments.length < commentsFromServer.length){

        let index = comments.length;

        comments.push(commentsFromServer[index]);

        this.setState({

          comments: comments

        });

      }

      */

     //case#2 : 제거

     if(comments.length > 0){

      comments.pop();

      this.setState({

        comments: comments

      });

    }

      else if (timer){

        clearInterval(timer);

      }

    }, 1000);

  }

 

  render(){

   ...

          return (

            <Comment

              //key값은 props로 제공해줄 수 없음.

              key={comment.id}

              //id값을 제공하여 key값처럼 활용

              id={comment.id}

              name={comment.name}

              content={comment.content} />

          )

    ...

}

export default App;

 

  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기