无论是基于还是基于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>
);
}
}所以,我的问题是:
如何将功能组件连接起来?
我可以更改方法(或者使用React ),我只需要始终拦截作为observe参数传递的组件上的更改。
发布于 2017-10-31 16:59:31
功能组件没有生命周期(目前还没有)。
与其直接处理functional,不如直接将functional封装在一个带有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;
}或者只是从这里复制代码。
https://stackoverflow.com/questions/46988652
复制相似问题