登录后我遇到重定向问题。它在我对结果进行硬编码时起作用,但是当我调用api来检查身份验证时,它会重定向到" / main"并返回当前页面" LoginForm"。
import React, { Component } from 'react';
import LoginForm from './components/login/LoginFormContainer';
import Main from './components/main/MainContainer';
import {
BrowserRouter as Router,
Switch,
Route
} from 'react-router-dom';
import './App.css';
class App extends Component {
render() {
return (
<Router>
<Switch>
<Route exact name="login" path="/" component={LoginForm} />
<Route exact name="main" path="/main" component={Main} />
</Switch>
</Router>
);
}
}
export default App;
并在我的loginPage中重定向到&#34; / main&#34;检查身份验证后
import React, { Component } from 'react';
import { Button, Form, Col, Row } from 'react-bootstrap';
import FieldGroup from '../common/FormGroup';
import { Redirect, Link } from 'react-router-dom';
import Logo from '../../img/zonLogo.svg';
class LoginForm extends Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleLoginClick = this.handleLoginClick.bind(this);
this.state = {
isLoggedIn: false,
username: "",
password: ""
};
}
handleLoginClick(e) {
var form = new FormData()
form.append("username", "xxxxx");
form.append("password", "xxxxx");
let self = this;
fetch('/login', {
method: 'POST',
body: form
}).then(function (response) {
if (response.status === 200) {
return response.json()
}
}).then(function (data) {
i f (data.user !== undefined && !data.user.isSuspended && !data.user.banned) {
self.setState({ isLoggedIn: true });
}
}).catch(function (error) {
console.log("Call report API error");
});
}
render() {
if (this.state.isLoggedIn) {
return <Redirect to="main" />;
}
return (
<div >
<Row>
<Col>
<Form onSubmit={this.handleLoginClick}>
<FieldGroup
id="username"
type="text"
placeholder="Username"/>
<FieldGroup
id="password"
type="password"
placeholder="Password"
/>
<Button type="submit" block> Log in</Button>
</Form>
</Col>
</Row>
</div >
);
}
}
export default LoginForm;
登录成功后,它会重定向到main,但会重定向回登录页面,但如果我硬编码就可以使用
handleLoginClick(e) {
self.setState({ isLoggedIn: true });
}