State & LifeCycle

hey hey·2021년 12월 7일
0

React 자료

목록 보기
3/18
post-thumbnail

State

  • React component의 상태 (data)
  • component에 대한 변경 가능한 데이터
  • state는 사용자가 정의한다. (렌더링하는 데이터만 사용)
  • state가 변하면 렌더링이 된다.
  • JavaScript 객체
  • 직접 변경하면 안된다 → setState()를 사용해야한다

State 정의하기

class App extends React.Component{
  constructor(props){
    super(props);
    this.state={
      comments:[
        {name:'hong', content:'홍'},
        {name:'onhg', content:'온흑'},
        {name:'nhgo', content:'느흑고'},
      ]
    };
  }
  render() {
    return (<div className="App" />)}}
<div>{this.state.comments}</div> 로 사용해도 되고

const {comments} = this.state 등록하면
<div>{comments}</div>         사용 가능

Component lifecycle

  • Mounting(출생) - componentDidMount
  • Updating(인생) - componentDidUpdate
  • Unmounting(사망) - componentWillUnmount

순차적 댓글 달기 ( setState, Mount)

const commentFromServer =[     comments에 넣을 값들
  {name:'hong', content:'홍'},
  {name:'onhg', content:'온흑'},
  {name:'nhgo', content:'느흑고'},
]
var timer;         타이머 사용할 예정

class App extends React.Component{
  **constructor(props){
    super(props);
    this.state={**      state에 빈 comment 등록
      **comments:[]
    };
  }**

  componentDidMount(){   첫 시작하면 실행
    let comments = this.state.comments;   state 내용 쉽게 사용하기
    timer = setInterval(()=>{    일정시간마다 함수를 실행 하겠다
						comments 내용이 3개가 될때까지
      if (comments.length < commentFromServer.length){ 
        let index = comments.length ; index는 0 부터 1,2..
        comments.push(commentFromServer[index]) comments에 새 값을 넣는다
        **this.setState({**    setState를 안하면 값이 바뀐지 몰라서
          **comments:comments**   렌더링이 되지 않는다
        **})**
      } else if (timer){
        clearInterval(timer);
      }
    },1000)
  }
profile
FE - devp

0개의 댓글