code

componentDidUpdate' 메서드를 사용하는 경우

starcafe 2023. 2. 27. 23:25
반응형

componentDidUpdate' 메서드를 사용하는 경우

을 개 , ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★componentDidUpdate★★★★★★ 。

이 방법을 사용해야 하는 일반적인 예가 있습니까?

단순한 데모가 아닌 실제 사례를 원합니다.

간단한 예로는 사용자로부터 입력 데이터를 수집한 후 Ajax를 사용하여 해당 데이터를 데이터베이스에 업로드하는 앱이 있습니다.다음은 간단한 예입니다(실행하지 않음 - 구문 오류가 있을 수 있음).

export default class Task extends React.Component {
  
  constructor(props, context) {
    super(props, context);
    this.state = {
      name: "",
      age: "",
      country: ""
    };
  }

  componentDidUpdate() {
    this._commitAutoSave();
  }

  _changeName = (e) => {
    this.setState({name: e.target.value});
  }

  _changeAge = (e) => {
    this.setState({age: e.target.value});
  }

  _changeCountry = (e) => {
    this.setState({country: e.target.value});
  }

  _commitAutoSave = () => {
    Ajax.postJSON('/someAPI/json/autosave', {
      name: this.state.name,
      age: this.state.age,
      country: this.state.country
    });
  }

  render() {
    let {name, age, country} = this.state;
    return (
      <form>
        <input type="text" value={name} onChange={this._changeName} />
        <input type="text" value={age} onChange={this._changeAge} />
        <input type="text" value={country} onChange={this._changeCountry} />
      </form>
    );
  }
}

에 '''가 state변경하면 데이터가 자동으로 저장됩니다.을 사용하다componentDidUpdate는 특히 DOM이 갱신되고 업데이트큐가 비워진 후에 조작이 필요한 경우에 편리합니다.복잡한 환경에서 가장 유용할 것입니다.renders ★★★★★★★★★★★★★★★★★」state또는 DOM이 변경되거나 마지막으로 실행해야 할 것이 필요한 경우.

위의 예는 다소 간단하지만 아마도 요점을 증명하고 있을 것이다.현재 자동 저장은 모든 키 입력에서 실행되므로 자동 저장 실행 횟수를 제한하는 것이 개선될 수 있습니다(예를 들어 최대 10초마다).

바이올린에 대한 시연도 해봤습니다.


상세한 것에 대하여는, 다음의 공식 문서를 참조해 주세요.

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

컴포넌트가 갱신되었을 때, 이것을 DOM 의 조작의 기회로 사용합니다.또한 현재 소품을 이전 소품과 비교한다면 네트워크 요청을 수행할 수 있습니다(소품이 변경되지 않은 경우 네트워크 요청은 필요하지 않을 수 있습니다.

경우에 따라서는 componentDidMount 또는 componentDidMount의 소품에서 상태 값을 추가할 수 있습니다.소품 변경 시 setState를 호출할 필요가 있지만 componentDidMount는 실행되지 않으며 componentDidUpdate도 호출하지 않습니다.이 경우 소품이 변경되었으므로 setS를 호출할 수 있습니다.componentDidUpdate에 새로운 소품으로 tate를 추가합니다.

이 라이프 사이클 메서드는 업데이트가 이루어지는 즉시 호출됩니다.componentDidUpdate() 메서드의 가장 일반적인 사용 사례는 프로펠러 또는 상태 변경에 대한 응답으로 DOM을 업데이트하는 것입니다.

이 라이프 사이클에서는 setState()를 호출할 수 있지만 이전 상태로부터의 상태 또는 변경을 확인하는 조건으로 랩해야 합니다.setState()를 잘못 사용하면 무한 루프가 발생할 수 있습니다.이 라이프 사이클 방법의 일반적인 사용 예를 나타내는 다음의 예를 참조해 주세요.

componentDidUpdate(prevProps) {
 //Typical usage, don't forget to compare the props
 if (this.props.userName !== prevProps.userName) {
   this.fetchData(this.props.userName);
 }
}

위의 예에서는 현재 소품을 이전 소품과 비교하고 있습니다.현재와 같은 소품에 변화가 있는지 확인하기 위해서입니다.이 경우 소품이 변경되지 않았다면 API 호출을 할 필요가 없습니다.

상세한 것에 대하여는, 다음의 공식 문서를 참조해 주세요.

componentDidUpdate(prevProps){ 

    if (this.state.authToken==null&&prevProps.authToken==null) {
      AccountKit.getCurrentAccessToken()
      .then(token => {
        if (token) {
          AccountKit.getCurrentAccount().then(account => {
            this.setState({
              authToken: token,
              loggedAccount: account
            });
          });
        } else {
          console.log("No user account logged");
        }
      })
      .catch(e => console.log("Failed to get current access token", e));

    }
}

사용한 적이 있다componentDidUpdate()하이차트로.

다음은 이 구성 요소의 간단한 예입니다.

import React, { PropTypes, Component } from 'react';
window.Highcharts = require('highcharts');

export default class Chartline extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      chart: ''
    };
  }

  public componentDidUpdate() {
    // console.log(this.props.candidate, 'this.props.candidate')
    if (this.props.category) {
      const category = this.props.category ? this.props.category : {};
      console.log('category', category);
      window.Highcharts.chart('jobcontainer_' + category._id, {
        title: {
          text: ''
        },
        plotOptions: {
          series: {
            cursor: 'pointer'
          }
        },
        chart: {
          defaultSeriesType: 'spline'
        },
        xAxis: {
          // categories: candidate.dateArr,
          categories: ['Day1', 'Day2', 'Day3', 'Day4', 'Day5', 'Day6', 'Day7'],
          showEmpty: true
        },
        labels: {
          style: {
            color: 'white',
            fontSize: '25px',
            fontFamily: 'SF UI Text'
          }
        },
        series: [
          {
            name: 'Low',
            color: '#9B260A',
            data: category.lowcount
          },
          {
            name: 'High',
            color: '#0E5AAB',
            data: category.highcount
          },
          {
            name: 'Average',
            color: '#12B499',
            data: category.averagecount
          }
        ]
      });
    }
  }
  public render() {
    const category = this.props.category ? this.props.category : {};
    console.log('render category', category);
    return <div id={'jobcontainer_' + category._id} style={{ maxWidth: '400px', height: '180px' }} />;
  }
}

(의 경우)전화해야 돼요.componentDidUpdate()componentDidMount()는 이미 호출되어 있습니다.

에서 후 componentDidUpdate()의 응답 할 수 .then((response) => this.setState({newValue: "here"}))prevProps ★★★★★★★★★★★★★★★★★」prevState스테이트를 새로운 값으로 설정하면 componentDidUpdate()가 다시 호출하기 때문에 무한 루프를 회피합니다.

베스트 프랙티스에는 componentDidMount()와 componentDidUpdate()의 2가지 부문이 있습니다.

@K.tin, componentDidUpdate()에서 setState를 호출하면 동일한 데이터를 다시 가져올 수 있습니까?

예를 들어 [id, data_for_id]는 상태이며 id는 클릭 카운터에 의해 변경할 수 있으며 data_for_id는 웹 API에서 가져옵니다.

다음으로 setState()에 의해 Id를 변경하고 componentDidUpdate()가 실행되며 data_for_id에 대해 setState가 실행되며 다른 componentDidUpdate()가 트리거됩니다.

componentDidUpdate가 처음 호출되면 prevState가 생성됩니다.ID = 0 및 상태.ID=1이므로 componentDidUpdate가 실행됩니다.두 번째 prev State는ID = 1 및 상태.ID = 1, componentDidUpdate는 완전히 회피할 수 있으며, wakeComponentUpdate()를 사용하여 구현할 수도 있습니다.

단, ID 변경용과 data_for_id 변경용 두 개의 리렌더가 발생합니다.이상적으로는 ID 변경을 검출하면 data_for_id를 가져와 [Id, data_for_id] 상태를 한 번에 변경해야 하며, 이 변경 ID 클릭에 대해 리렌더가 한 번만 발생합니다.

따라서 일반적으로 componentDidUpdate()에서는 setState를 실행하지 않습니다.또한 여러 상태 컴포넌트의 변경이 관련되어 있는 경우에는 변경을 한 곳에서 동시에 실행하고 setState를 한 번에 실행해야 합니다.

이건 내 추론일 뿐이야.저는 리액트 전문가가 아니기 때문에 코멘트 부탁드립니다.

사용할 때는 조심해야 합니다.API를 여러 번 호출하기 때문입니다.경우에 따라서는 무제한 콜

언급URL : https://stackoverflow.com/questions/38759703/when-to-use-componentdidupdate-method

반응형