如何删除componentWillUnmount()中的函数调用?

时间:2018-09-12 07:42:56

标签: javascript reactjs components lifecycle

我不确定是否根据问题表达了我的问题,但也许代码会有所帮助:

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 :(得分:0)

默认情况下不会取消承诺(我想您会兑现承诺) 完全可以,您有一些选择:

选项1-使用蓝鸟

// 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