Как убрать вызов функции в componentWillUnmount ()? - PullRequest
0 голосов
/ 12 сентября 2018

Я не уверен, что сформулировал свой вопрос в соответствии с моей проблемой, но, возможно, код поможет:

import React from 'react';
import PropTypes from 'prop-types';
import { Component } from 'kawax-js';

class Reference extends React.Component {

 state={fileDisplayed:""}

 static propTypes = {
 getFile: PropTypes.func.isRequired,
 content: PropTypes.object
 }

 static defaultProps = {
 content: Object()
 }

 componentDidMount = async() => {
 this.props.getFile(this.props.match.params.refHash);
 }

 componentWillUnmount() {
 }
 ....

При попытке переключения между компонентами возникает ошибка утечки памяти.Как убедиться, что вызов функции из componentDidMount отменяется в componentWillUnmount после того, как я хочу вернуться к моему предыдущему компоненту?

1 Ответ

0 голосов
/ 12 сентября 2018

Обещания не могут быть отменены по умолчанию (я полагаю, ваше получение проходит через обещание), хотя у вас есть несколько вариантов:

Вариант 1 - Использовать Bluebird

// Bluebird promise cancellation
const promise = new Promise((resolve, reject, onCancel) => {
  const id = setTimeout(resolve, 1000);
  onCancel(() => clearTimeout(id));
});
// use the promise as usual
promise.then(() => console.log('done'));
// anytime later
promise.cancel();

Вариант 2 - использовать другое обещание

/ a basic stitched-together CancelToken
// creation mechanism
function createToken() {
  const token = {};
   token.promise = new Promise(resolve => {
    cancel = (reason) => {
      // the reason property can be checked
      // synchronously to see if you're cancelled
      token.reason = reason;
      resolve(reason);
    });
  };
  return { token, cancel };
}
// create a token and a function to use later.
const { token, cancel } = createToken();
// your functions that return promises would also take
// a cancel token
function delay(ms, token) {
  return new Promise(resolve => {
    const id = setTimeout(resolve, ms);
    token.promise.then((reason) => clearTimeout(id));
  });
};

Вариант 3 - Использовать Rx-подписки

// create a subscription to use with your promise
const subscription = new Rx.Subscription();
const promise = new Promise(resolve => {
  const id = setTimeout(resolve, 1000);
  // add teardown logic to the subscription
  subscription.add(() => clearTimeout(id));
});
// use the promise as usual
promise.then(() => console.log('done'));
// call unsubscribe at any point to cancel
subcscription.unsubscribe();

Вариант 4 - Дитч обещает и просто использует Observables!

// create an observable, you can return teardown logic
const source$ = new Rx.Observable(observer => {
  const id = setTimeout(() => observer.next(), 1000);
  return () => clearTimeout(id);
};
// subscribing gives you a subscription
const sub = source$.subscribe(() => console.log('done'));
// cancel at any time later
sub.unsubscribe();

Ссылка: https://medium.com/@benlesh/promise-cancellation-is-dead-long-live-promise-cancellation-c6601f1f5082

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...