我正在使用switch标签来路由不同的路由
<Switch>
<Route extact path = "/" component = {LoginPage} />
<Route path = "/home" component= {HomePage} />
</Switch>
但这只会加载路径/的第一个组件,并且/ home也会加载登录页面,并且什么都不会发生,并且homehome组件也不会加载到/ home路径上!
我尝试在切换之前使用浏览器路由器标签,首先尝试加载首页,也仅加载首页组件相同
App.js
import React,{ Component } from 'react';
import {BrowserRouter, Switch ,Route} from 'react-router-dom';
import LoginPage from './components/LoginPage';
import HomePage from './components/HomePage';
class App extends React.Component {
render(){
return (
<Switch>
<Route extact path = "/" component = {LoginPage} />
<Route path = "/home" component= {HomePage} />
</Switch>
);
}
}
export default App;
LoginPage.js
import React, {Component} from 'react';
import HomePage from './HomePage';
import Logo from '../image/Logo1.png'
import {Redirect} from 'react-router-dom';
import axios from 'axios';
class LoginPage extends Component{
render(){
return(
<div className='loginWindow'>
<form >
<img src={Logo} /><br/>
<input type="text" onChange = {(event) => this.setState({usrname:event.target.value })} name="usrname" placeholder="Username"/><br/>
<input type="Password" onChange = {(event) => this.setState({usrpass:event.target.value })} name="usrpass" placeholder="Password"/><br/>
<input type="button" value="Login" onClick={event=>this.Login(event)} />
</form>
</div>
);
}
}
export default LoginPage;
HomePage.js
import React,{Component} from 'react';
import Footer from './Footer/Footer';
import Header from './Header/Header';
class HomePage extends Component{
render(){
return(
<div id="HomePage">
<Header />
<h1>hello</h1>
<Footer />
</div>
)
}
}
export default HomePage;
预期
访问/应该加载登录页面
访问/ home应该加载主页
答案 0 :(得分:1)
import React,{ Component } from 'react';
import {BrowserRouter as Router , Switch ,Route} from 'react-router-dom';
import LoginPage from './components/LoginPage';
import HomePage from './components/HomePage';
class App extends React.Component {
render(){
return (
<Router>
<Switch>
<Route exact path = "/" component = {LoginPage} />
<Route path = "/home" component= {HomePage} />
</Switch>
</Router>
);
}
}
export default App;
导入路由器并添加它!
答案 1 :(得分:0)
您做对了,但拼写错误,
exact
(正确)=> extact
(您正在使用)