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

Hit*_*nds 13 javascript reactjs

当React卸载Component时,无论是基于组件还是基于组件,我都需要始终进行拦截.FunctionalClass

这是我的情况:

function observe(component) {
  const p = component.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 component;
}

class Comp extends React.Component {

  render() {

    return (<h1>Hello World</h1>);
  }
}

class App extends React.Component {

  render() {
    const active = this.state && this.state.active;
    const toggle = () => this.setState({
      active: !active,
    });

    return (
      <div>
        <button onClick={toggle}>Toggle</button>
        <hr />
        {active && observe(<Comp />)}
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,正如您可以轻松看到的,我可以在每次<Comp />卸载时挂钩.这正是我需要的.

当这<Comp />是一个功能组件时,事情将发生巨大变化:

function observe(component) {
  const p = component.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 component;
}



function Comp() {

  return (<h1>Hello World</h1>);
}


class App extends React.Component {

  render() {
    const active = this.state && this.state.active;
    const toggle = () => this.setState({
      active: !active,
    });

    return (
      <div>
        <button onClick={toggle}>Toggle</button>
        <hr />
        {active && observe(<Comp />)}
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是:

如何挂钩功能组件?

我可以改变方法(或使用React内部Apis),我只需要总是拦截作为参数传递的组件的更改observe.

Mar*_*son 14

你不能.功能组件没有生命周期(尚未).

而不是直接搞乱功能组件,为什么不直接将功能组件包装在具有HOC的类中.你可以toClass为此重复使用.

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;
}
Run Code Online (Sandbox Code Playgroud)

或者只是从这里复制代码.