2016-12-03 68 views
0

我很難搞清楚如何在我的反應路由器中正確實現onChange。我想要做的就是改變我想重定向到首頁。下面這段代碼:React路由器OnChange重定向

import React, { Component } from 'react'; 
import ReactDOM from 'react-dom'; 
import App from './App'; 
import Home from './Home'; 
import Post_Form from './Post_Form'; 

import * as Firebase from 'firebase'; 
import Config from './utils/config.js'; 
import Auth from './utils/auth.js'; 

import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router'; 

class Root extends Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
     }; 
    } 

    routeChange(nextPathname, nextState, replace, cb) { 
     replace({ 
     pathname: '/home', 
     state: {nextPathname: nextState.location.pathname} 
     }); 
     cb(); 
    } 

    render() { 
     return (
      <Router history = {browserHistory}> 
       <Route path = "/" component = {App} onChange={this.routeChange.bind(this)}> 
       <IndexRoute component = {Home} /> 
       <Route path = "home" component = {Home} /> 
       <Route path ="post-form" component={Post_Form} /> 
       <Route path="*" component={Home}/> 
       </Route> 
      </Router> 
     ) 
    } 
} 


ReactDOM.render(<Root />, document.getElementById('root')); 

當單擊導航我得到

Uncaught RangeError: Maximum call stack size exceeded 

回答

1

我想調用來替換被觸發另一個變化事件,並再次調用routeChange。這就是爲什麼你的堆棧大小被超過。

你可以嘗試在調用replace之前檢查你是否已經在家。事情是這樣的:

if(nextState.location.pathname != '/home'){ 
     replace({ 
    pathname: '/home', 
    state: {nextPathname: nextState.location.pathname} 
    }); 
    } 

我做類似上面的東西在我的項目,儘管的OnEnter,但我認爲它應該的onChange正常工作。

+0

非常感謝你,我唯一缺少的就是條件。 – BonTheBeerman

+0

歡迎您!如果你願意的話,請把它標記爲答案) – Mustafa