Web/Js

componentDidUpdate

Calssess 2022. 3. 4. 18:26
반응형

componentDidUpdate(prevProps, prevState)

< Props Update >

props가 업데이트될 때의 과정입니다. 업데이트되기 전에 업데이트가 발생하였음을 감지하고, componentWillReceiveProps 메소드가 호출됩니다. 그 후 shouldComponentUpdate, componentWillUpdate가 차례대로 호출된 후, 업데이트가 완료(render)되면 componentDidUpdate가 됩니다.
이 메소드들은 첫 번째 인자로 바뀔 props에 대한 정보를 가지고 있습니다. componentDidUpdate만 이미 업데이트되었기 때문에 바뀌기 이전의 props에 대한 정보를 가지고 있습니다.

componentDidUpdate(prevProps, prevState) { // 이전 props, state에 대한 정보
    if (prevProps.todos.length !== this.props.todos.length) {
      // 이전 todo리스트의 길이가 달라지면(추가,삭제) 상태변화
      this.setState({
        dataSource: this.state.ds.cloneWithRowsAndSections(
          _.groupBy(this.props.todos, 'createdAt'),
        ),
      })
    }
    if (prevState.isTodoList !== this.state.isTodoList) {
      // 탭 이동
      if (!this.state.isTodoList) { // 완료된 탭일 때,
        this.setState({ // 완료된 탭만 필터된 datasource
          dataSource: this.state.ds.cloneWithRowsAndSections(
            _.groupBy(_.filter(this.props.todos, (todo) => todo.isDone), 'createdAt'),
          ),
        })
      } else {
        this.setState({
          dataSource: this.state.ds.cloneWithRowsAndSections(
            _.groupBy(this.props.todos, 'createdAt'),
          ),
        })
      }
    }
  }

 

참고링크
https://www.zerocho.com/category/React/post/579b5ec26958781500ed9955

 

출처: https://feel5ny.github.io/2017/12/23/log_002/

반응형