当用户刷新其他页面时,我需要重定向到主页。这是我为页面刷新添加事件监听器的尝试。但它不起作用,我有 Router.js?cf42:125 Uncaught RangeError: Maximum call stack size exceeded
在浏览器中。你能告诉我如何处理这个错误吗?
import {browserHistory} from 'react-router';
class MyComponent extends React.Component {
constructor(props, context) {
super(props, context);
this.onUnload = this.onUnload.bind(this);
}
componentDidMount() {
window.addEventListener('beforeunload', this.onUnload);
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.onUnload);
}
onUnload() {
browserHistory.push('/');
}
render() {
...
}
}
UPD:我已修复 RangeError。现在
MyComponent
的页面被重定向到主页,但之后它再次打开。我认为这是因为重定向不会停止页面刷新。
最佳答案
试试 window.location.href
而不是 browserHistory.push
.这会有所帮助。
onUnload() {
window.location.href = "/";
}
这是一个例子:https://stackblitz.com/edit/react-rbfoic?file=src/App.js
关于javascript - 当您尝试刷新其他页面时,React js重定向到主页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46361536/