Javascript 在锚定标记单击react后,组件将卸载,但不会被调用
每当组件卸载时,我需要将url保存在本地存储中:Javascript 在锚定标记单击react后,组件将卸载,但不会被调用,javascript,reactjs,Javascript,Reactjs,每当组件卸载时,我需要将url保存在本地存储中: componentWillUnmount(){ console.log("componentWillUnmount will call here."); console.log("window.redirect.url",window.location.pathname); localStorage.setItem("prevUrl",window.location.pathname);
componentWillUnmount(){
console.log("componentWillUnmount will call here.");
console.log("window.redirect.url",window.location.pathname);
localStorage.setItem("prevUrl",window.location.pathname);
}
在另一种情况下,如果存在单击锚定标记的情况,则不调用上述方法:
<a href="/differentpage">differentpage </a>
我无法执行卸载方法。有什么方法可以执行卸载吗?您可以将一个方法绑定到a标记,然后在handle方法中创建一个日志,然后重定向到新路径重定向到SPA上下文之外的其他页面将导致您退出react生命周期。单击“刷新”按钮时,就好像希望完成此循环一样。
不过,您可以使用
e.preventDefault()
将处理程序设置到此锚定标记,以停止默认行为,然后对状态执行操作,并且只有在完成后,才将窗口路径重定向到通过e.target.href
提供的链接。请记住,将窗口位置重定向到SPA外部的其他页面后,您将丢失任何状态更新。
代码示例:
const styles={
fontFamily:'无衬线',
textAlign:'中心',
};
类应用程序扩展了React.Component{
onClick=e=>{
e、 预防默认值();
//对状态执行任何您想要的操作,但请记住,一旦您将窗口重定向到此上下文之外,您将丢失所有数据(考虑使用本地存储的持久状态?)
window.location=e.target.href;
}
render(){
返回(
重定向我!{'\u2728'}
);
}
}
ReactDOM.render(,document.getElementById('root'))代码>
是不同页面
是SPA中的路线(反应路由器)还是不同页面?