簡體   English   中英

React-router browserHistory.push不重定向

[英]React-router browserHistory.push doesn't redirect

嘗試使用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>
    );

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

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

  • Router hashHistory替換為browserHistory ,如下所示:

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

如果您使用的是最新的react-router API,則需要使用:

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

訪問this.props時,可能需要將此綁定到您的函數(注意: may ):

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

有關此主題的所有信息,請參考以下問題:

使用React Router以編程方式導航

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM