source

리액트 훅 및 컴포넌트 라이프 사이클 등가

ittop 2023. 3. 8. 21:49
반응형

리액트 훅 및 컴포넌트 라이프 사이클 등가

에 상당하는 것은 무엇입니까?componentDidMount,componentDidUpdate,그리고.componentWillUnmount리액트 후크를 사용한 라이프 사이클 후크useEffect?

componentDidMount

두 번째 인수로 빈 어레이를 전달합니다.useEffect()마운트 상에서만 콜백만 실행합니다.

function ComponentDidMount() {
  const [count, setCount] = React.useState(0);
  React.useEffect(() => {
    console.log('componentDidMount');
  }, []);

  return (
    <div>
      <p>componentDidMount: {count} times</p>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>
    </div>
  );
}

ReactDOM.render(
  <div>
    <ComponentDidMount />
  </div>,
  document.querySelector("#app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>

componentDidUpdate

componentDidUpdate()는 업데이트 직후에 호출됩니다.이 메서드는 초기 렌더에 대해 호출되지 않습니다. useEffect첫 번째 렌더를 포함한 모든 렌더에서 실행됩니다.따라서 다음과 같은 조건을 충족하고 싶다면componentDidUpdate, 를 사용해야 합니다.useRef컴포넌트를 한 번 장착했는지 확인합니다.좀 더 엄격해지고 싶다면useLayoutEffect()단, 동기적으로 기동합니다.대부분의 경우,useEffect()충분할 겁니다.

이 답변은 Tholle에서 영감을 얻었고, 모든 것은 Tholle에게 돌아간다.

function ComponentDidUpdate() {
  const [count, setCount] = React.useState(0);

  const isFirstUpdate = React.useRef(true);
  React.useEffect(() => {
    if (isFirstUpdate.current) {
      isFirstUpdate.current = false;
      return;
    }

    console.log('componentDidUpdate');
  });

  return (
    <div>
      <p>componentDidUpdate: {count} times</p>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>
    </div>
  );
}

ReactDOM.render(
  <ComponentDidUpdate />,
  document.getElementById("app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>

componentWillUnmount

useEffect의 callback 인수로 콜백을 반환하면 마운트 해제 전에 콜백이 호출됩니다.

function ComponentWillUnmount() {
  function ComponentWillUnmountInner(props) {
    React.useEffect(() => {
      return () => {
        console.log('componentWillUnmount');
      };
    }, []);

    return (
      <div>
        <p>componentWillUnmount</p>
      </div>
    );
  }
  
  const [count, setCount] = React.useState(0);

  return (
    <div>
      {count % 2 === 0 ? (
        <ComponentWillUnmountInner count={count} />
      ) : (
        <p>No component</p>
      )}
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>
    </div>
  );
}

ReactDOM.render(
  <div>
    <ComponentWillUnmount />
  </div>,
  document.querySelector("#app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>

React 문서에서:

React 클래스의 라이프 사이클 메서드에 익숙한 경우 useEffect Hook을 componentDidMount, componentDidUpdate 및 componentWillUnmount가 결합된 것으로 생각할 수 있습니다.

이 말은 다음을 의미합니다.

componentDidMount는 일종의useEffect(callback, [])

component Did Update는useEffect(callback, [dep1, dep2, ...])- dep 배열이 React에 "dep하나가 변경되면 렌더링 콜백을 실행합니다."

componentDidMount + componentDidUpdate는 일종의useEffect(callback)

componentWillUnmount는 콜백에서 반환되는 함수의 일종입니다.

useEffect(() => { 
    /* some code */
    return () => { 
      /* some code to run when rerender or unmount */
    }
)

Dan Abramov의 블로그 표현과 제 블로그의 몇 가지 추가사항을 통해:

이 훅을 사용할 수는 있지만, 정확히 동등한 것은 아닙니다.와는 달리componentDidMount그리고.componentDidUpdate소품과 스테이트를 캡처합니다.따라서 콜백 내부에서도 특정 렌더링의 소품과 상태를 확인할 수 있습니다(즉,componentDidMount초기 소품 및 상태)"최신"을 보고 싶다면, 그것을 심판에게 쓸 수 있다.하지만 보통 코드를 구성하기 위한 더 간단한 방법이 있습니다.대체 함수라고 가정하는 반환 함수componentWillUnmount또한 이 함수는 컴포넌트가 재기동될 때마다 실행되며 컴포넌트가 마운트 해제될 때마다 실행되므로 완전히 동일한 함수는 아닙니다.효과의 정신적 모델은 컴포넌트 라이프 사이클과 다르므로 정확한 동등물을 찾으려 하면 도움이 아닌 혼란이 발생할 수 있습니다.생산성을 향상시키려면 "효과에 대한 생각"이 필요하며, 라이프 사이클 이벤트에 대한 대응보다는 동기 구현에 더 가깝습니다.

Dan 블로그의 예:

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setTimeout(() => {
      console.log(`You clicked ${count} times`);
    }, 3000);
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

여기에 이미지 설명 입력

클래스 구현을 사용하는 경우:

componentDidUpdate() {
  setTimeout(() => {
    console.log(`You clicked ${this.state.count} times`);
  }, 3000);
}

여기에 이미지 설명 입력

this.state.count는 항상 특정 렌더에 속하는 카운트가 아닌 최신 카운트를 가리킵니다.

간단한 설명을 위해 시각적 참조를 보여드리고자 합니다.

여기에 이미지 설명 입력

위 그림에서 알 수 있듯이 다음과 같은 용도가 있습니다.

componentDidMount:

useEffect(() => {        
   console.log('componentWillMount');
}, []);

componentDidUpdate:

useEffect(() => {        
   console.log('componentWillUpdate- runs on every update');
});

useEffect(() => {        
   console.log('componentWillUpdate - runs if dependency value changes ');
},[Dependencies]);

component will Unmount :

  useEffect(() => {
    return () => {
        console.log('componentWillUnmount');
    };
   }, []);

다음은 React Hooks FAQ에서 클래스 라이프 사이클 메서드에 대응하는 Hooks를 나열한 요약입니다.

constructor: 함수 구성 요소에는 생성자가 필요하지 않습니다.콜의 상태를 초기화할 수 있습니다.초기 상태를 계산하는 데 비용이 많이 드는 경우 함수를 다음 주소로 전달할 수 있습니다.useState.

getDerivedStateFromProps: 대신 렌더링 중에 업데이트를 예약합니다.

shouldComponentUpdate: 아래의 React.memo를 참조하십시오.

render: : : : : : : : : : : : : : 。

componentDidMount,componentDidUpdate,componentWillUnmount : 후크는 이러한 모든 조합을 표현할 수 있습니다(흔하지 않은 경우 포함).

componentDidCatch ★★★★★★★★★★★★★★★★★」getDerivedStateFromError: 이 메서드에 대한 Hook 대응은 아직 없지만 곧 추가됩니다.


componentDidMount

useEffect(() => { /*effect code*/ }, []);

[]이 효과는 마운트 시 한 번만 실행됩니다.일반적으로 종속성을 지정하는 것이 좋습니다.레이아웃 타이밍이 다음과 같다.componentDidMount(대부분의 경우 필요하지 않음)를 참조해 주십시오.

componentWillUnmount

useEffect(() => { /*effect code*/ ; return ()=> { /*cleanup code*/ } }, [deps]); 

componentWillUnmount청소의 효과에 해당합니다.

componentDidUpdate

const mounted = useRef();
useEffect(() => {
  if (!mounted.current) mounted.current = true;
  else {
    // ... on componentDidUpdate 
  }
});

.componentDidUpdate(대부분의 경우 필요하지 않음)를 참조해 주십시오.상세한 것에 대하여는, 투고도 참조해 주세요.componentDidUpdate후크 등가물

언급URL : https://stackoverflow.com/questions/53254017/react-hooks-and-component-lifecycle-equivalent

반응형