当您尝试刷新其他页面时,React js 重定向到主页
2017-09-22
21803
当用户刷新其他页面时,我需要重定向到主页。我尝试添加事件侦听器来刷新页面。但是它不起作用,并且我的浏览器中出现
Router.js?cf42:125 Uncaught RangeError: Maximum call stack size reached
。您能告诉我如何应对此错误吗?
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() {
...
}
}
更新:我已修复 RangeError。现在
MyComponent
的页面已重定向到主页,但之后它会再次打开。我认为发生这种情况是因为重定向不会停止页面刷新。
3个回答
尝试使用
window.location.href
代替
browserHistory.push
。这会有所帮助。
onUnload() {
window.location.href = "/";
}
以下是示例:
Pulsara Sandeepa
2020-11-12
您需要绑定
onUnload()
- 将以下内容添加到您的构造函数中:
this.onUnload = this.onUnload.bind(this);
此外,侦听器的正确事件名称是
onbeforeunload
StudioTime
2017-09-22
componentWillMount() {
sessionStorage.reload = true;
}
render() {
if(sessionStorage.reload && history.location.pathname!=='/') {
console.log(this.props);
sessionStorage.reload = "";
history.push('/login');
}
return (
<Router history={ history }>
<div className="App">
<Switch>
<>
<Route path="/" exact strict component={ Loginpage } />
<Route path="/mapview" exact component={ GoogleMap } />
<Route path="/dashboard" exact component={ Dashboard } />
<Route path="/tripList" exact component={ TripList } />
<Route path="/createTrips" exact component={ CreateTrips } />
<Route path="/trace" exact component={ trace } />
<Route path="/vehicleinfo" component={ vehicleinfo } />
<Route path="/MyPeople" component={ MyPeople } />
<Route path="/AddForm" component={ MyPeople } />
<Route path="/ListView" component={ ListView } />
<Route path="/fleetAlerts" component={FleetAlerts} />
<Route path="/login" exact component={ Loginpage } />
</>
</Switch>
</div>
</Router>
) }
karthick s
2019-12-02