我有一个小型的React应用。 在应用程序中,我有一个登录表单。
我有3页,如下面App
组件中的路由器所示。
问题是我无法访问/
路径旁边的任何URL。
如果我尝试输入/login
或/mechinasetup
,则会收到404错误。
现在,在localhost中它可以很好地工作,我可以输入所有路径,但是在服务器上,我只能输入/
路径。
如果我在主页上输入Link
,它将带我进入登录页面。
我不想在主页上添加登录页面的链接,我希望用户能够通过键入/login
来查看/login
。
login
和MechinaSetup
组件中的中,我有一个重定向脚本,该脚本检查本地存储,并且根据那里的值,它将在需要时重定向用户(下面的代码)。
如何在不使用<Link>
的情况下进行重定向?
import React, { Component } from 'react';
import { BrowserRouter , Route, Switch } from 'react-router-dom';
import Calc from './components/Calc';
import Login from './components/auth/Login';
import MechinaSetup from './components/adminarea/MechinaSetup';
import './App.css';
class App extends Component {
render() {
return (
<BrowserRouter basename="/calc">
<Switch>
<Route exact path="/" component={Calc} />
<Route path="/login" component={Login} />
<Route path="/mechinasetup" component={MechinaSetup} />
</Switch>
</BrowserRouter>
);
}
}
export default App;
简而言之,这是应该重定向登录页面的功能
redirectUser = auth => {
if (auth === false) {
this.props.history.push("/login");
}
};
我按照此问题的建议使用history.push
:
Programmatically navigate using react router
整个组件
登录组件-名为 redirectUser
的重定向功能import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Redirect, Link } from 'react-router-dom';
import {connect} from 'react-redux';
import { userLogedIn } from '../../actions';
import {
Button,
Form,
FormGroup,
FormControl,
Col,
Checkbox,
ControlLabel,
HelpBlock,
Container,
Row
} from 'react-bootstrap';
class LoginForm extends Component {
state={
username: '',
password: '',
data: [],
auth: false
}
componentWillMount(){
const auth = localStorage.getItem('auth');
localStorage.getItem('auth') === 'true' ?
this.props.userLogedIn(this.props): console.log('xxx');
}
componentDidUpdate(){
this.redirectUser(this.props.user.auth);
}
onSubmitLogin = (event) => {
// let auth = this.state.auth;
event.preventDefault();
fetch('./api/user_switch/' + this.state.username +
'/'+ this.state.password )
.then(response => response.json())
.then(json => {
if(json.count > 0)
{
this.props.userLogedIn(this.props)
}
})
.catch(error => console.log('parsing faild', error))
}
onChange(event){
this.setState({
[event.target.name]: event.target.value
})
}
redirectUser = (auth) =>{
if(auth === true){
localStorage.setItem('auth', true);
localStorage.setItem('username', this.state.username);
localStorage.setItem('password', this.state.password);
this.props.history.push("/mechinasetup");
}
}
render() {
return (
<Container id="LoginForm" className="align-middle" style={loginForm}>
<h1 className="text-center">כניסה לניהול מחשבון מכינה</h1>
<Row className="show-grid justify-content-center">
<Col xs={8}>
<Form>
<FormGroup controlId="formHorizontalusername">
<Col xs={12} componentclass={'aa'} className="text-right">
דואר אלקטרוני:
</Col>
<Col xs={12}>
<FormControl
ref="username"
name="username"
type="text"
onChange={this.onChange.bind(this)}
placeholder="הקלד דואר אלקטרוני"/>
</Col>
</FormGroup>
<FormGroup controlId="formHorizontalPassword" >
<Col xs={12} componentclass={'cc'} className="text-right">
סיסמא:
</Col>
<Col xs={12}>
<FormControl ref="password" name="password" type="password" onChange={this.onChange.bind(this)} placeholder="הקלד סיסמא"/>
</Col>
</FormGroup>
<FormGroup>
<Col >
<Button onClick={this.onSubmitLogin} type="submit" className="full-width-btn" id="loginSubmit" block>התחבר</Button>
</Col>
</FormGroup>
</Form>
</Col>
</Row>
</Container>
);
}
}
const loginForm = {
height: '100vh'
}
const mapStateToProps = (state) =>{
return{
user: state.user
}
}
const mapDispatchToProps = dispatch => {
return {
userLogedIn: (params) => dispatch(userLogedIn(params))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(LoginForm);
MechinaSetup组件-名为redurectUser
的重定向功能
import React, { Component } from "react";
import { connect } from "react-redux";
import {
Container,
Form,
Button,
Col,
Row,
Table,
striped,
bordered,
hover
} from "react-bootstrap";
import { logOut, addCourse } from "../../actions";
import Courses from "./AdminCourses";
import Head from '../layout/Header';
class MechinaSetup extends Component {
state = {
id: Math.random(),
courseName: '',
courseWeeklyHours: '',
courseType: false
};
redirectUser = auth => {
if (auth === false) {
this.props.history.push("/login");
}
};
onChange = e => {
this.setState({
[e.target.name]: e.target.value
});
};
render() {
const headerTitle = 'מחשבון מכינה';
const Logout = true;
return (
<div>
<Head headerTitle={headerTitle} isLogOut={Logout}/>
{/* if user is not logged in redirect him to login page */}
{this.redirectUser(this.props.user.auth)}
<Courses />
</div>
);
}
}
const mapStateToProps = state => {
return {
user: state.user,
courses: state.courses
};
};
export default connect(
mapStateToProps,
{ logOut }
)(MechinaSetup);
答案 0 :(得分:0)
我遵循了这个答案https://stackoverflow.com/a/43470639/3471458
并将HashRouter
替换为import React, { Component } from 'react';
import { BrowserRouter , Route, Switch, HashRouter } from 'react-router-dom';
import Calc from './components/Calc';
import Login from './components/auth/Login';
import MechinaSetup from './components/adminarea/MechinaSetup';
import './App.css';
class App extends Component {
render() {
return (
<HashRouter basename="/">
<Switch>
<Route exact path="/" component={Calc} />
<Route path="/login" component={Login} />
<Route path="/mechinasetup" component={MechinaSetup} />
</Switch>
</HashRouter>
);
}
}
export default App;
,
现在我的App组件看起来像这样:
{{1}}