Javascript React Intercept组件卸载(功能组件和类组件)

Javascript React Intercept组件卸载(功能组件和类组件),javascript,reactjs,Javascript,Reactjs,我需要在React卸载组件时始终拦截,无论该组件是基于功能的还是基于类的组件 我的情况如下: 功能观察(部件){ const p=component.type.prototype; const delegate=p.componentWillUnmount | |函数noop(){}; 如果(!委托){ p、 componentWillUnmount=函数(){ log(“我将要卸载”); 返回delegate.apply(这个,参数); } p、 componentWillUnmount.\u

我需要在React卸载组件时始终拦截,无论该组件是基于
功能的
还是基于
类的组件

我的情况如下:

功能观察(部件){
const p=component.type.prototype;
const delegate=p.componentWillUnmount | |函数noop(){};
如果(!委托){
p、 componentWillUnmount=函数(){
log(“我将要卸载”);
返回delegate.apply(这个,参数);
}
p、 componentWillUnmount.\uuu=true;
}
返回组件;
}
类Comp.Component{
render(){
返回(你好世界);
}
}
类应用程序扩展了React.Component{
render(){
const active=this.state&&this.state.active;
const toggle=()=>this.setState({
活动:!活动,
});
返回(
切换

{active&&observe()} ); } }
现在,正如您很容易看到的,每当
卸载时,我都可以挂机这正是我需要的

成为一个功能组件时,情况将发生巨大变化:

功能观察(部件){
const p=component.type.prototype;
const delegate=p.componentWillUnmount | |函数noop(){};
如果(!委托){
p、 componentWillUnmount=函数(){
log(“我将要卸载”);
返回delegate.apply(这个,参数);
}
p、 componentWillUnmount.\uuu=true;
}
返回组件;
}
函数Comp(){
返回(你好世界);
}
类应用程序扩展了React.Component{
render(){
const active=this.state&&this.state.active;
const toggle=()=>this.setState({
活动:!活动,
});
返回(
切换

{active&&observe()} ); } }
所以,我的问题是:

如何连接功能组件?
我可以更改方法(或使用React内部API),我只需要始终截获作为
观察
参数传递的组件上的更改。功能组件还没有生命周期

与其直接处理功能组件,不如将功能组件包装在一个带有HOC的类中。您可以使用“重新组合”进行此操作

function observe(component) => {
  const classComponent = toClass(component):
  const p = classComponent.type.prototype;
  const delegate = p.componentWillUnmount || function noop() {};

  if(!delegate.__decorated) {
    p.componentWillUnmount = function() {
      console.log('I am going to be unmounted');

      return delegate.apply(this, arguments);
    }

    p.componentWillUnmount.__decorated = true;
  }

  return classComponent;
}

或者从中复制代码。

如果需要生命周期方法,则应将功能组件转换为类。如果代码与功能组件一起工作,请检查idk。faict,这是不可行的。您可以查看这个库,它基本上是向基于函数的类添加生命周期方法。^这是。高阶组件(HOC)是解决这一问题的方法。
function observe(component) => {
  const classComponent = toClass(component):
  const p = classComponent.type.prototype;
  const delegate = p.componentWillUnmount || function noop() {};

  if(!delegate.__decorated) {
    p.componentWillUnmount = function() {
      console.log('I am going to be unmounted');

      return delegate.apply(this, arguments);
    }

    p.componentWillUnmount.__decorated = true;
  }

  return classComponent;
}