当 React 卸载组件时,我需要始终拦截,无论它是否是 Functional
或 Class
基于组件。
这是我的案例:
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>
);
}
}
现在,如您所见,我每次都能挂机 <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>
);
}
}
所以,我的问题是:
如何 Hook 功能组件?
我可以改变方法(或使用 React 内部 Apis),我只需要始终拦截作为参数传递给 observe
的组件的更改。 .
最佳答案
你不能。功能组件还没有生命周期。
与其直接搞乱功能组件,不如将功能组件包装在一个带有 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;
}
或者直接复制 here 中的代码.
关于javascript - React Intercept 组件卸载(功能组件和类组件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46988652/