kok202
React 기본 (3)

2019. 8. 16. 02:28[정리] 기능별 개념 정리/React

데이터 변경을 Render 에 어떻게 반영시킬까?

this.state 에 있는 값을 변경한다고 렌더링 까지 자동으로 호출 되어 반영 되는 것은 아니다.

setState 메서드를 호출해서 변경해야만 렌더링 까지 자동으로 호출 되어 반영이 된다.

 

 


배열과 객체에 데이터를 추가 삭제하는 경우가 생겨서 이를 반영하고 싶을 때는?

기존의 배열, 객체에 push, pop 한다고 렌더링이 반영되지 않는다.

배열과 객체의 데이터 변경을 반영하고 싶으면 새로운 것으로 대체해야 반영이된다. (Immutable)

내부적으로 객체의 주소를 비교해서 변경 여부를 판단하고 렌더링을 할지 말지 결정하기 때문이 아닐가 싶다.

Immutable 을 만들 땐 배열은 spread operator 를 쓸 수 있다.

Immutable 을 만들 땐 객체는 Object.assign() 을 쓰는 것이 좋다.

 

 

 

데이터 변경 예제

 

코드

class MyList extends React.Component {
  render() {
    return (
      <ul>
        <li onClick={this.props.onClick}> kok202</li>
        <li onClick={this.props.onClick}> kok303</li>
        <li onClick={this.props.onClick}> kok404</li>
      </ul>
    )
  }
}

class MyLog extends React.Component {
  render() {
    return(
      <div>
        <h4>로그 정보 : {this.props.selectedName}</h4>
      </div>
     )
  }
}

class MyBlog extends React.Component {
  constructor() {
    super();
    this.state = {selectedName:""}
  }
  
  myHandler(event) {
    console.log("name is ", event.target.innerText)
    this.setState({selectedName: event.target.innerText})
  }
  
  render() {
    return (
      <div>
        <h2>My Blog posts</h2>
        <MyList onClick={this.myHandler.bind(this)}/>
        <MyLog selectedName={this.state.selectedName}/>
      </div>
    )
  }
}

ReactDOM.render(
  <MyBlog/>, 
  document.querySelector("#wrap")
);

 

 



React component lifecycle simplify

  1. constructor
  2. componentWillMount
  3. render
  4. componentDidMount

출처 : https://d2.naver.com/content/images/2017/03/helloworld-201702-React2-04-1.png




렌더링 성능 개선

React 는 render 함수가 쉽게 자주 불리기 때문에 re-rendering 횟수를 줄여야한다.

shouldComponentUpdate 를 잘 활용하면 render 함수를 부를지 안부를지 결정할 수 있다.

라이프 사이클 내의 shouldComponentUpdate 의 위치를 확인해보자.

shouldComponentUpdate 이를 통해 렌더링 횟수를 줄일 수 잇다.

shouldComponentUpdate(nextProp, nextState) {
  return (nextState.msg !== this.state.msg);
}

 

 

 

이후의 스텝은 가능하면 이 포스팅을 따라하자

튜토리얼 : https://reactjs.org/tutorial/tutorial.html

전체 코드 : https://codepen.io/gaearon/pen/gWWZgR?editors=0010

 

 

'[정리] 기능별 개념 정리 > React' 카테고리의 다른 글

React 강의 정리 (3,4)  (0) 2019.08.18
React 강의 정리 (2)  (0) 2019.08.18
React 강좌 정리 (1)  (0) 2019.08.17
React 기본 (2)  (0) 2019.08.16
React 기본 (1)  (0) 2019.08.16