programing

반응 구성 요소가 마운트 해제되었는지 확인하는 방법이 있습니까?

projobs 2021. 1. 18. 07:27
반응형

반응 구성 요소가 마운트 해제되었는지 확인하는 방법이 있습니까?


반응 구성 요소를 마운트 해제해야하는 사용 사례가 있습니다. 그러나 어떤 경우에는 특정 반응 구성 요소가 다른 기능에 의해 마운트 해제됩니다. 따라서 부품을 분리하기 전에 부품이 장착되었는지 확인해야합니다.


이후 isMounted()공식적으로 사용되지되고, 당신은 당신의 구성 요소에서이 작업을 수행 할 수 있습니다 :

componentDidMount() { 
  this._ismounted = true;
}

componentWillUnmount() {
   this._ismounted = false;
}

자체 state변수 를 유지하는이 패턴은 ReactJS 문서에 자세히 설명되어 있습니다. isMounted는 Antipattern 입니다.


Shubham 답변은 isMounted안티 패턴 사용을 중지하기 위해 코드를 전환해야하는 사람들을 위해 react에서 제안한 해결 방법이라고 생각합니다 .

이것이 반드시 나쁜 것은 아니지만이 문제에 대한 실제 해결책을 나열하는 것이 좋습니다.

Shubham이 링크 한 기사 는 이러한 안티 패턴을 피하기위한 두 가지 제안을 제공합니다. 필요한 것은 컴포넌트가 마운트 해제 될 때 setState를 호출하는 이유에 따라 다릅니다.

컴포넌트에서 Flux 스토어를 사용하는 경우 componentWillUnmount에서 구독을 취소해야합니다.

class MyComponent extends React.Component {
  componentDidMount() {
    mydatastore.subscribe(this);
  }
  render() {
    ...
  }
  componentWillUnmount() {
    mydatastore.unsubscribe(this);
  }
}

ES6 프라 미스를 사용하는 경우 취소 가능하도록 프라 미스를 래핑해야 할 수 있습니다.

const cancelablePromise = makeCancelable(
  new Promise(r => component.setState({...}}))
);

cancelablePromise
  .promise
  .then(() => console.log('resolved'))
  .catch((reason) => console.log('isCanceled', reason.isCanceled));

cancelablePromise.cancel(); // Cancel the promise

makeCancelable링크 된 기사에서 자세히 알아보세요 .

결론적으로 변수를 설정하고 구성 요소가 마운트되었는지 확인하여이 문제를 패치하지 말고 문제의 원인으로 이동하십시오. 다른 일반적인 경우에 대해 의견을 제시하십시오.


또 다른 해결책은 Refs를 사용하는 것 입니다. React 16.3 이상을 사용하는 경우 render 함수에서 최상위 항목을 참조하십시오.

그런 다음 ref.current가 null인지 확인하십시오.

예:

class MyClass extends React.Component {
  constructor(props) {
    super(props);
    this.elementRef = React.createRef();
  }

  checkIfMounted() {
     return this.elementRef.current != null;
  }

  render() {
    return (
      <div ref={this.elementRef} />
    );
  }
}

pollingAPI 를 중지 할 방법을 찾고 있었기 때문에 여기에 왔습니다 .

문서를 반응 덮 않는 websocket경우가 있지만 폴링 하나.

내가 일했던 방식

// React component

React.createClass({
    poll () {
        if (this.unmounted) {
            return
        }
        // otherwise, call the api
    }
    componentWillUnmount () {
        this.unmounted = true
    }
})

효과가있다. 도움이되기를 바랍니다.

이것에 대한 실패한 테스트 케이스를 알고 있다면 알려주세요 =]


같은 아이디어이지만 다른 구현

/**
 * component with async action within
 * 
 * @public
 */
class MyComponent extends Component {
    constructor ( ...args ) {
        // do not forget about super =)
        super(...args);
        // NOTE correct store "setState"
        let originSetState = this.setState.bind(this);
        // NOTE override
        this.setState = ( ...args ) => !this.isUnmounted&&originSetState(...args);
    }
    /**
     * no necessary setup flag on component mount
     * @public
     */
    componentWillUnmount() {
        // NOTE setup flag
        this.isUnmounted = true;
    }
    /**
     *
     * @public
     */
    myCustomAsyncAction () {
        // ... code
        this.setState({any: 'data'}); // do not care about component status
        // ... code
    }

    render () { /* ... */ }
}


구성 요소가 마운트 해제된다는 것을 발견했습니다.이 변수를 채우십시오.

if(!this._calledComponentWillUnmount)this.setState({vars});


당신이 사용할 수있는:

myComponent.updater.isMounted(myComponent)

"myComponent"는 반응 구성 요소의 인스턴스입니다. 컴포넌트가 마운트 된 경우 'true'를 반환하고 그렇지 않은 경우 'false'를 반환합니다.

  • 이것은 지원되지 않는 방법입니다. componentWillUnmount 에서 모든 비동기 / 이벤트를 구독 취소하는 것이 좋습니다 .

ReferenceURL : https://stackoverflow.com/questions/39767482/is-there-a-way-to-check-if-the-react-component-is-unmounted

반응형