与之前的问题类似:Firefox Extension - onPopupClose event?,我有一个简单的弹出窗口组件,用于订阅和取消订阅计时器。我正在使用React,如果没有在窗口componentWillUnmount
上与unload
一起显式调用它,就无法调用ReactDOM.unmountComponentAtNode
。
componentWillUnmount()在卸载和销毁组件之前立即被调用。在此方法中执行任何必要的清除,例如使计时器无效,取消网络请求或清除在componentDidMount()中创建的所有订阅。
因此我认为应该调用该事件,因为在卸载窗口时该组件将被破坏。
import React from 'react';
import ReactDOM from 'react-dom';
// Due to how web-extensions seperate different web-extension components
// (popups, content scripts, and background scripts) you must use methods
// like getBackgroundPage to share the namespace of variables in other
// contexts.
const BG = browser.extension.getBackgroundPage();
class DashBoard extends React.Component {
constructor(props) {
super(props);
this.timer = BG.timer;
this.Store = BG.Store;
this.state = { secondsElapsed: 0 };
this.setSecondsElapsed = this.setSecondsElapsed.bind(this);
}
setSecondsElapsed(seconds) {
this.setState({ secondsElapsed: seconds });
}
componentDidMount() {
console.log("Component Mounting");
this.timer.subscribe(this.setSecondsElapsed);
}
componentWillUnmount() {
console.log("Unmounting");
this.timer.unsubscribe(this.setSecondsElapsed);
}
render() {
return (
<React.Fragment>
<p>Current Session Time Spent: {this.state.secondsElapsed}</p>
</React.Fragment>
);
}
}
ReactDOM.render(<DashBoard/>, document.getElementById("content"));
window.addEventListener("unload", function () {
ReactDOM.unmountComponentAtNode(document.getElementById("content"));
});