在同一页面上react-router渲染组件

IT技术 javascript reactjs react-router react-redux
2021-05-03 02:10:40

react router在我的项目中使用,当我点击登录按钮时,它rendersApp组件的内容,但将它们显示在same page. 我想new page在我点击时显示login,帮帮我

import React, { Component } from 'react';
import * as service from '../services/service';
import '../App.css'
import '../index.css'
import App from'../App'
import { Link, Redirect, Router, Route, browserHistory,IndexRoute } from 'react-router';
// import createHistory from 'history/createBrowserHistory'

class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      messages: []
    }
  }
  onSubmit() {
    browserHistory.push('/world');
    }
  render() {
    const { messages } = this.state;
    return (
      <div className="App">
        <header>
          <h2> Doctor Login Page </h2>
        </header>
        <form>

        <Router history={browserHistory}>
        <Route path="/world" component={App}/>
      </Router>
          <br /><br /><br />
          Username: <input name='email' placeholder='Email' /><br /><br />
          Password: <input name='password' placeholder='Password' type='password' />
          <br /><br />
          <button onClick={() => this.onSubmit()}>Login</button>
        </form>
      </div>
    );
  }
}

export default Login;
2个回答

看起来你想通过两种方式解决这个问题

1) 使用 react-router 库中的“精确路径”属性

<Route exact path="/world" component={App}/>

2) 删除路由下面的代码并将其放入组件本身并声明自己的路由,因为上面的代码运行主路由器并在路由器下方保留静态 JSX。

<Route exact path="/" component={Login}/>
<Route exact path="/world" component={App}/>

确保将最具体的路线放在顶部。一旦找到匹配项,React 路由将扫描每条路由,如果您没有使用“精确”关键字,它将重定向到该路由。

例子:

<Route path="/world" component={App}/>
<Route path="/" component={Login}/>

我以前遇到过这个问题,如果将来有人遇到这个问题,重新排序路线是解决方案。