javascript - 在 react 中单击 anchor 标记后,组件将卸载而不会被调用

标签 javascript reactjs

每当组件卸载时,我都需要将 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/

相关文章:

Javascript、url对象压缩

javascript - Controller 中定义的函数(javascript)与scope.function( Angular 函数)的区别

javascript - 为什么将 React 组件存储为变量或状态是不好的设计实践

javascript - 'react-router' 不包含名为 'browserHistory' 的导出。来自/src/App.js

javascript - 我可以在 react 中使用 useEffect 钩子(Hook)从子级设置父级状态吗

javascript - Three.js 如何确保模型加载后加载其他 javascript 文件

javascript:多维数组操作

javascript - 这个链接函数如何知道 "tabsCtrl"引用了什么?

javascript - 无法在 chrome-extension 中从 executeScript 发送数据

reactjs - 在 Typescript 中使用 useContext 传递状态