2016-08-12 85 views
2

試圖使用browserHistory.push方法以編程方式更改我的路線。反應路由器browserHistory.push不重定向

它會更改路線(每個瀏覽器地址欄)但不更新視圖。

這裏是我的代碼 App.jsx

const AppStart = React.createClass({ 

    render: function() { 
    return (
     <MuiThemeProvider> 
     <Router history={hashHistory}> 
      <Route path="/" component={Main}> 
      <Route path="experiences" component={Experiences} /> 
      <Route path="people" component={Profiles} /> 
      <Route path="login" component={Login} /> 
      <IndexRoute component={Home}/> 
      </Route> 
     </Router> 
     </MuiThemeProvider> 
    ); 
    } 
}); 

ReactDOM.render(
    <AppStart />, 
    document.getElementById('app') 
); 

組件:

handleLoginRedirect(e) { 
    browserHistory.push('/experiences'); 
    }, 

    render() { 
    return (
     <div className='row'> 
     <div className='col-sm-10 col-sm-offset-1'> 
      <form role='form'> 
      <RaisedButton label="Redirect" onClick={this.handleLoginRedirect} /> 
      </form> 
     </div> 
     </div> 
    ); 
+1

其實只是想通了,不能相信。我沒有看到我使用hashHistory而不是瀏覽器歷史裏面的,更改爲browserHistory修復了所有內容 – zsayn

回答

4

當您推入browserHistory時,您的路由器配置使用hashHistory

很容易錯過這樣的事情,這是可以理解的。

  • 更換hashHistorybrowserHistoryRouter像這樣:

<Router history={browserHistory}>

全段:

const AppStart = React.createClass({ 

    render: function() { 
    return (
     <MuiThemeProvider> 
     <Router history={browserHistory}> 
      <Route path="/" component={Main}> 
      <Route path="experiences" component={Experiences} /> 
      <Route path="people" component={Profiles} /> 
      <Route path="login" component={Login} /> 
      <IndexRoute component={Home}/> 
      </Route> 
     </Router> 
     </MuiThemeProvider> 
    ); 
    } 
}); 
+0

是的,這是問題,謝謝,幾乎一旦我在這裏發佈,幾個小時後調試:) – zsayn

1

如果您正在使用最新的反應,路由器API,你需要使用:

this.props.history.push('/path/goes/here'); 

您可能需要綁定給你的函數訪問this.props(注:可能):當

onClick={this.handleLoginRedirect.bind(this)} 

請參考以下問題關於這一主題的所有信息:

Programmatically navigate using react router

+0

當你說最新時,你的意思是什麼版本? AFAIK,browserHistory.push支持,以下是反應路由器文檔中的使用示例:https://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.0.0.md#navigating-inside-深度嵌套的組件。 HTH – KumarM