programing

componentDidUpdate와 componentDidMount

golfzon 2023. 3. 10. 22:59
반응형

componentDidUpdate와 componentDidMount

다음 조건에 해당하는 경우 입력 요소가 포커스를 맞춰야 합니다.

  • DOM 사용 가능
  • 속성이 변경되었습니다.

질문:.둘 다에 코드를 넣어야 합니까?componentDidUpdate그리고.componentDidMount아니면 그냥componentDidUpdate충분할까요?

    private makeSureInputElementFocused() {
        if (this.props.shouldGetInputElementFocused && this.inputElement !== null) {
            this.inputElement.focus();
        }

    }

    componentDidMount() {
        this.makeSureInputElementFocused(); // <-- do i need this?
    }
    componentDidUpdate() {
        this.makeSureInputElementFocused();
    }

둘 다 써야 돼요.

component Did Mount()

componentDidMount()는 컴포넌트가 마운트된 직후에 호출됩니다.DOM 노드가 필요한 초기화가 여기에 있어야 합니다.원격 엔드포인트에서 데이터를 로드해야 하는 경우 네트워크 요청을 인스턴스화할 수 있습니다.이 메서드로 상태를 설정하면 재렌더링이 트리거됩니다.

componentDidUpdate()

componentDidUpdate()는 업데이트 직후에 호출됩니다.이 메서드는 초기 렌더에 대해 호출되지 않습니다.

또, 이 파일을,render()항상 초점을 확인하고 싶기 때문에 당신의 경우에 적합한 방법인 것 같습니다.그럼 안 넣어도 돼componentDidMount()그리고.componentDidUpdate()

각각의 조건에 따라 코드를 1개의 함수 안에 배치해야 합니다.

  • DOM을 사용할 수 있습니다.componentDidMount
  • 속성이 변경되었습니다.componentDidUpdate

그래서 두 기능 모두 안쪽에 배치해야 합니다.
또 다른 옵션은 전화하는 것입니다.setState()안에서.componentDidMount,하도록componentDidUpdate호출됩니다.

componentDidUpdate는, 초기 렌더링시에 콜 되지 않습니다(https://reactjs.org/docs/react-component.html#componentdidupdate) 를 참조해 주세요).따라서, 예시와 같이 2 회 콜 할 필요가 있습니다.

component Did Mount()

componentDidMount()는 컴포넌트가 마운트된 직후에 호출됩니다.이 메서드는 한 번만 렌더링하며 DOM 노드를 필요로 하는 모든 초기화가 여기에 있어야 합니다.이 메서드로 상태를 설정하면 재렌더링이 트리거됩니다.

componentDidUpdate()

componentDidUpdate()는 업데이트가 발생할 때마다 즉시 호출됩니다.이 메서드는 초기 렌더에 대해 호출되지 않습니다.

아래 예에서 더 많은 것을 이해할 수 있습니다.

import React from 'react';

class Example extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
  componentDidMount() {

    //This function will call on initial rendering.
    document.title = `You clicked ${this.state.count} times`;

  }
  componentDidUpdate() {
     document.title = `You clicked ${this.state.count} times`;
   }

  render(){
    return(
      <div>
      <p>You clicked {this.state.count} times</p>
      <button onClick={() => this.setState({ count: this.state.count + 1 })}>
        Click me
      </button>
    </div>
    )
  }
}
export default Example;

두 가지 방법을 모두 코멘트 및 코멘트 해제하면 이해할 수 있습니다.

React v16.7.0-alpha에서는 useEffect 후크를 사용할 수 있습니다.

import React, { useEffect, useRef } from "react";

function InputField() {
  const inputRef = useRef();

  useEffect(() => {
    inputRef.current.focus();
  });

  return <input ref={inputRef} />;
}

문서에서:

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

주의: 전술한 바와 같이 클래스 베이스의 컴포넌트에서는 동작하지 않습니다.

언급URL : https://stackoverflow.com/questions/46686386/componentdidupdate-vs-componentdidmount

반응형