useEffect 후크 고난 + 치트 시트

어제 this project 을 작업하면서 useFetchCollections 에 포함된 논리가 끝없이 호출된다는 점에서 결함이 있음을 깨달았습니다.

이것은 firestore의 무료 일일 허용 할당량에 도달하는 잘못된 결과를 가져왔습니다!

거의 24시간 동안 클라우드 데이터베이스에 대한 읽기 접근이 금지되었습니다!!!!

따라서 이 문제를 해결하기 위해 다음과 같은 커밋을 푸시했습니다.

1) 무한 루프를 수정하고,
2) 이제 데이터베이스에서 데이터를 가져오는 대신 로컬 json 파일에서 collections 데이터를 사용합니다. 하나의 데이터 소스 또는 다른 하나)

process.env.NODE_ENV 후크 시련



이 루프는 데이터 가져오기가 in this file history에서 볼 수 있듯이 production 후크 내부에 있기 때문에 발생했습니다.

  const fetchCollections = fetchCollectionsAsync(setCollectionsState);

  useEffect(() => {
    fetchCollections();
  }, [fetchCollections]);
  return collectionsState;
};


문제는 배열 내부에 종속성으로 development를 포함하는 것이었습니다(useEffect가 취하는 두 번째 인수). 거기에 포함하지 않으면 React lib가 경고를 발행했습니다.

React Hook useEffect has a missing dependency: `fetchCollections`.
Either include it or remove the dependency array. 
If `fetchCollections` changes too often, find the parent component that defines it and wrap that definition in useCallback


이 특정 문제에서는 useEffect가 한 번만 실행되도록 해야 했기 때문에 내가 발행한 수정 사항은 다음과 같습니다.

  useEffect(() => {
    fetchCollectionsAsync(setCollectionsState);
  }, []);


수정 사항은 다음을 수행할 수 있습니다.

A) React 경고를 제거하고
B) 전체 구성 요소 수명 주기에서 한 번만 실행되도록 빈 종속성 배열을 제공하여 필요에 따라 동작하도록 fetchCollections 가져옵니다.

useEffect에 종속성 배열을 전달하지 않는 경우



경고 메시지에서 찾은 제안 중 하나는 useEffect 입니다.

약간의 연구 끝에 useEffect가 트리거되기를 원할 때 이 종속성 배열을 생략해야 한다는 것이 밝혀졌습니다.

  • 해당 구성 요소가 렌더링을 완료할 때마다
  • useEffect가 호출될 때마다

  • 구성 요소 렌더링에 대한 알림



    구성 요소는 다음 중 하나일 때 다시 렌더링됩니다.
  • 소품 교환
  • 상태 변경
  • 상위 구성 요소가 다시 렌더링됩니다.

  • 종속성 배열 치트 시트 제거



    React 팀의 수석 개발자인 Dan Abramov는 이를 좋아하지 않지만 여기에 클래스 기반 구성 요소 수명 주기 측면에서 사용 사례를 "매핑"useEffect하는 치트 시트가 있습니다.

    ComponentDidMount




    //Class
    componentDidMount() {
        console.log('I just mounted!');
    }
    
    //Hooks
    useEffect(() => {
        console.log('I just mounted!');
    }, [])
    


    ComponentWillUnmount




    //Class
    componentWillUnmount() {
        console.log('I am unmounting');
    }
    
    //Hooks
    useEffect(() => {
        return () => console.log('I am unmounting');
    }, [])
    


    ComponentWillReceiveProps




    
    //Class
    componentWillReceiveProps(nextProps) {
        if (nextProps.count !== this.props.count) {
            console.log('count changed', nextProps.count);
        }
    }
    
    //Hooks
    useEffect(() => {
        console.log('count changed', props.count);
    }, [props.count])
    
    

    좋은 웹페이지 즐겨찾기