当您尝试刷新其他页面时,React js重定向到主页

时间:2017-09-22 09:39:19

标签: javascript reactjs react-router

当用户刷新其他页面时,我需要重定向到主页面。这是我尝试为页面刷新添加事件监听器。但它不起作用,我在浏览器中有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的页面被重定向到主页面,但之后它再次打开。我认为这是因为重定向不会阻止页面刷新。

5 个答案:

答案 0 :(得分:0)

您需要绑定onUnload() - 将以下内容添加到构造函数中:

this.onUnload = this.onUnload.bind(this);

此外,侦听器的正确事件名称为onbeforeunload

答案 1 :(得分:0)

如果您使用的是React-Router,并且您的主组件路径为/

onUnload() {
    this.context.router.push('/');
}

确保您的路线文件也正确。

const routes = (
<Route path="/" component={App}>
 <IndexRedirect to="/home" component{Home}/>
  //all other routes
</Route>
)

答案 2 :(得分:0)

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>
)  }

答案 3 :(得分:0)

尝试使用window.location.href而不是browserHistory.push。这会有所帮助。

onUnload() {
       window.location.href = "/";
}

这里是一个例子:

https://stackblitz.com/edit/react-rbfoic?file=src/App.js

答案 4 :(得分:0)

试试这个简单的方法

 import {  useHistory } from "react-router-dom";
   let history = useHistory();

  function your(){
     let confirm = () => {
alert(
  `you will get redirect to home on click ok`
);
window.location.reload(history.push("/"));
         };

        return(
        <button className="redirect_confirm" onClick={confirm}>
          Confirm
        </button>
            )
                   }