每当组件卸载时,我都需要将 url 保存在本地存储中:
componentWillUnmount(){
console.log("componentWillUnmount will call here.");
console.log("window.redirect.url",window.location.pathname);
localStorage.setItem("prevUrl",window.location.pathname);
}
还有一种情况,就是有点击 anchor 标签的情况,没有调用上面的方法:
<a href="/differentpage">differentpage </a>
我无法执行卸载方法。有什么办法可以执行卸载吗?
最佳答案
重定向到 SPA 上下文之外的不同页面将导致您跳出 React 生命周期。这就像点击刷新按钮时期望经历这个循环。
不过,您可以做的是使用 e.preventDefault()
为该 anchor 标记设置一个处理程序以停止默认行为,然后使用该状态执行您的操作,只有在完成后才重定向窗口在这种情况下,通过 e.target.href
提供的链接的路径。
但请记住,在将窗口位置重定向到 SPA 之外的其他页面后,您将丢失所有状态更新。
代码示例:
const styles = {
fontFamily: 'sans-serif',
textAlign: 'center',
};
class App extends React.Component {
onClick = e => {
e.preventDefault();
// do whatever you want with the state, but keep inmind you will lose all the data once you redirect the window out of this context (consider persistent state with local storage?)
window.location = e.target.href;
}
render(){
return(
<div style={styles}>
<a href="https://google.com" onClick={this.onClick}>click!</a>
<h2>Redirect me! {'\u2728'}</h2>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
关于javascript - 在 react 中单击 anchor 标记后,组件将卸载而不会被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46067579/