从组件导航到另一个组件

时间:2016-09-30 17:43:21

标签: reactjs react-router

我有登录组件和仪表板。我的应用程序入口点是登录页面。登录成功后,我想转到主页面(仪表板和导航)。

我尝试了以下但是它不起作用。登录后无法移动到仪表板。
我的登录组件是

var React = require('react');
var {Link} = require('react-router');
var Dashboard = require('Dashboard');

var Login = React.createClass ({
onFormSubmit: function(e){
    e.preventDefault();
   <Dashboard /> 
},
render: function(){
  return (
<div>
  <h1 className="text-center">Login</h1>
  <form onSubmit={this.onFormSubmit}>
        <input type="text" ref="username"/>

        <button className="button">Login</button>
  </form>
 </div>
 )
 } 
 });

module.exports = Login;

我的仪表板组件

 var React = require('react');
 var Nav = require('Nav');

 var Dashboard = (props) => {
   return (
     <div>
      <Nav/>
      <div className="row">
        <div className="columns medium-6 large-4 small-centered">
        {props.children}
      </div>
     </div>
   </div>
 );
}

module.exports = Dashboard;

主app.jsx文件是

var React = require('react');
var ReactDOM = require('react-dom');
var {Route, Router, IndexRoute, hashHistory} = require('react-router');
var Login = require('Login');
var Dashboard = require('Dashboard');
var About = require('About');
var Examples = require('Examples');

ReactDOM.render(
  <Router history={hashHistory}>
  <Route path="/" component={Login}>
     <Route component={Dashboard}>
       <Route path="about" component={About}/>
       <Route path="examples" component={Examples}/>
    </Route>
   </Route>
  </Router>,
 document.getElementById('app')
 );

1 个答案:

答案 0 :(得分:1)

您的onFormSumit()应该是这样的

onFormSubmit: function(e){
    e.preventDefault();
   window.location.href = '/dashboard'
},

app.jsx 中的<Router/>应该是这样的

<Router history={hashHistory}>
   <Route path="/" component={Login} />
   <Route path="dashboard" component={Dashboard} />
   <Route path="about" component={About}/>
   <Route path="examples" component={Examples}/>
 </Router>

这会使浏览器在表单提交时重定向到/dashboard。重定向的网址(/dashboard)将由<Router/>捕获,并且将呈现该path的组件。

[更新]

express中,您需要添加路径,以便始终返回index.html页面。添加此

app.get(['/', '/dashboard'], function(req, res){
  res.sendfile('./path to your index.html file')
})

或者您也可以执行以下操作

app.get('*', function(req, res){
   res.sendfile('./path to your index.html file')
})

如需进一步阅读,请查看this