티스토리 뷰

Tip and Error/ReactJS

State (동적 데이터) & setState

geonwoopaeng@gmail.com 2021. 7. 18. 22:19

> React

  • HTML의 class -> className
  • react는 자동적으로 나의 class component의 render method를 실행 한다.
  • react는 state를 refresh하고 render function을 호출한다

 

 

캡처

> State

https://smilejh.tistory.com/90

 

[React] 3. Component의 Props 와 State

1. Component의 props 와 state 리액트 컴포넌트에서 다루는 데이터는 props와 state로 나뉜다. props는 부모 컴포넌트에서 자식 컴포넌트로 전달하는 값이다 (-> 부모 컴포넌트에서 자식 컴포넌트로 전달하

smilejh.tistory.com

  • 동적 데이터와 함께 작업할 때 만들어져 변하는 데이터, 존재하지 않는 데이터
  • => dynamic data
  • Component의 내부
  • props에 따라 Component를 구현하는 내부의 state
  • (props: React가 유저가 정의한 컴포넌트를 나타내는 요소를 볼 때 JSX 속성을 이 컴포넌트에 단일 객체(props)로 전달)
//App.js

class App extends Component {
    constructor(props) {
        //constructor: render보다 먼저 실행하며 Component를 초기화 하고 싶은 코드를 작성
        super(props);
        this.state = {
            // state 초기화
            subject: {title: 'WEB', sub:'HELLO'},
            contents: [
                {id:1, title:'HTML', desc:'HTML info'},
                {id:2, title:'CSS', desc:'CSS info'}
            ]
        }
    }
    render() {
        return (
        <div className="App">
            <Subject>
                title={this.state.subject.title}
                sub={this.state.subject.sub}
            </Subject>
            <TOC data={this.state.contents}></TOC>
        </div>);
    }
}


---------------------

//TOC.js
class TOC extends Component {
    render() {
        var lists = [];
        var data = this.props.data;
        var i = 0;
        while (i < data.length) {
            lists.push(<li><a href={"/contnet/" + data[i].id}>{data[i].title}</a></li>);
            i = i + 1;
        }
        return (
        <nav>
          <ul>
            {lists}
          </ul>
        </nav>
        );
    }
}

> setState

state를 바꿀때 사용

  • setState를 호출하면 component를 호출하고 먼저 render를 호출한 다음 update가 완료되면 ComponentDidUpdate가 실행=> render -> componentDidMount() 실행
  • => setState -> component -> render -> update -> CompnentDidUpdate

캡처


> life cycle method

  • react가 component를 생성하고 없애는 방법

> Mounting

  • 태어난 것
Constructor()
  • js에서 class 만들때 호출
  • Component가 mount(태어날 때)될 때, Component가 screen에 표시될 때, Component가 나의 website에 갈 때 호출한다.

> Updating

  • 일반적인 업데이트
  • state를 변경할 때 마다 update
반응형
공지사항
최근에 올라온 글