我有一个主要组件,我已经初始化了一个路由器,我想将其重定向到登录组件,但是当我转到http://localhost:3000/login时,它没有显示登录组件,但仍显示了该应用程序。 .js,可能是什么原因
APP.JS
import React, { Component } from 'react';
import './index.css';
import './styles.css';
import ReactDOM from 'react-dom';
import LoginComponent from './components/LoginComponent';
import { BrowserRouter as Router, Route } from 'react-router-dom'
class Apps extends Component {
constructor(props) {
super(props);
// Don't do this!
this.state = {
showing: true,
Login: false,
Signup: false,
Members: false
};
}
render() {
return (
<div>
<div className="container" style={{ display: (this.state.showing ? 'block' : 'none') }}>
<div >A Single Page web application made with react</div>
</div>
<LoginComponent view={this.state.Login} />
<div className="buttons">
<a href='' ref="login" onClick={this.Login_onclick.bind(this)} >{this.state.Login? "back": "Login"}</a>
</div>
<Router>
<Route path="/login" component={LoginComponent}/>
</Router>
</div>
);
}
Login_onclick(e) {
this.setState({Login: !this.state.Login });
e.preventDefault(); //alert(e.target.value);
this.setState({showing: !this.state.showing});
// this.setState({ref: !ref});
}
}
export default Apps;
LoginComponent.js
class LoginComponent extends Component {
constructor(props){
super(props);
this.state = ({details: {}});
}
componentDidMount() {
// console.log('Component DID MOUNT!')
this.ajaxloader();
}
ajaxloader() {
fetch("./login.php")
.then(res => res.json())
.then(
(result) => {
console.log(result);
});
}
render() {
return (
<div className="login" style={{ display: (this.props.view ? 'block' : 'none') }}>
<h3>Login</h3><br/>
Username: <input type="text" ref="username"/><br/>
Password <input type="password" ref="password"/>
<button value="Login" ref="login" >Login</button>
</div>
);
}
}
export default LoginComponent;
答案 0 :(得分:1)
<Router>
<switch>
<Route path="/login" component={LoginComponent}/>
</switch>
</Router>
并确保按照以下说明从 react-router-dom 导入交换机。
import { BrowserRouter as Router, Link, Route, Switch } from 'react-router-dom';