【发布时间】:2018-05-19 12:27:41
【问题描述】:
我的组件this.props.save(); 什么时候componentWillUnmount?但是,如果我将页面留在不同选项卡中的外部链接,它不会触发 componentWillUnmount
我的组件
export default class AutoSave extends React.Component {
constructor(props) {
super(props);
this.setIntervalId = null;
}
componentDidMount() {
if (!window.onbeforeunload) {
window.onbeforeunload = () => {
this.props.save();
};
}
this.setIntervalId = setInterval(() => this.props.save(), this.props.intervalInMs);
}
componentWillUnmount() {
this.props.save();
clearInterval(this.setIntervalId);
}
render() {
return <span className="saving">Last saved at {now()}</span>;
}
}
我的链接是这样的
<Link href="http://www.google.com" target="_blank">
Google Link
</Link>
当用户点击链接时如何保存组件?这是一个 react/redux 应用程序。
【问题讨论】:
-
打开新标签不会触发
componentWillUnmount()或onbeforeunload。在这两种情况下,因为您的应用仍然在原始选项卡中打开。 React 不会在您关闭或离开页面之前立即卸载组件,因此即使页面关闭,componentWillUnmount()也不会执行任何操作。onbeforeunload仅在您从页面在同一选项卡 中导航离开 或关闭选项卡/窗口时触发。如果您想在每次用户单击您的按钮时可靠地调用this.props.save(),那么只需向按钮添加一个onClick处理程序。 -
你能告诉我怎么做吗?
标签: javascript reactjs ecmascript-6 redux state