TIL46.componentDidUpdate

조연정·2020년 11월 15일
0
post-thumbnail

많이 들어봤지만 한번도 사용해본 적 없는 componentDidUpdate를 이번 프로젝트에서 드디어 사용해보았다. 정리해보자!

componentDidUpdate 개념

이전 상태와 현재 상태를 비교하여 구성 요소 업데이트를 한다.
componentDidUpdate()후에 호출 componentDidMount()되며 상태가 변경 될 때 일부 작업을 수행하는 데 유용하게 사용된다.
componentDidUpdate()에는 prevProps와 prevState 이전 상태의 인자가 들어간다.

언제 사용할 수 있을까?

componentDidUpdate()이전 상태와 현재 상태가 변경된 상태에서 외부 API를 호출해야하는 경우에 사용할 수 있다.
API에 대한 호출은 변경되는 상태에 따라 달라지는데, 상태 변경이 없으면 API가 호출되지 않는다.

componentDidUpdate(prevProps, preState) {
    if (prevProps.location.search !== this.props.location.search) {
      fetch(`${KM_URL}/products/coffees${this.props.location.search}`)
        .then((res) => res.json())
        .then((res) => {
          this.setState({
            filteredCoffeeCount: res.filteredCoffeeCount,
            filteredCoffeeList: res.filteredCoffeeList,
            offset: 1,
            show: res.filteredCoffeeList.length < 18 ? false : true,
          });
        });
    }
  }

이번 프로젝트에서 componentDidUpdate 사용할 기회가 있어서 좋았다.

필터카테고리에서 사용자가 어떤 항목을 골랐냐에 따라 필터에 해당하는 원두리스트를 보여줘야하는 하는 로직이 필요했다.
그때마다 이전의props(this.props.location.search)와 현재의 props를 비교해서 데이터를 다시 요청하고, 데이터가 변경되면 재렌더해서 보여준다.

profile
Lv.1🌷

0개의 댓글