Я новичок в реактивной среде и работаю над небольшим проектом для знакомства.В данный момент я работаю над страницей входа в систему и успешно смог получить ответ, независимо от того, был он успешным или нет.Проблема, с которой я сталкиваюсь, состоит в том, что, как только я получаю ответ, я не знаю, как сохранить и прочитать то, что находится в ответе, без console.log.
import React from 'react';
import { connect } from 'react-redux';
import { Button, Input } from 'reactstrap';
import { IsEmpty } from '../../helpers/utils';
import { userActions } from '../../actions/user.actions';
import LoginLayoutComponent from '../layouts/loginLayout';
class LoginFormComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
Username: '',
Password: '',
submitted: false,
errors: {}
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleValidation = this.handleValidation.bind(this);
}
handleChange(e) {
const { name, value } = e.target;
this.setState({ [name]: value });
}
handleSubmit(e) {
e.preventDefault();
let response = null;
let errors = {};
if (this.handleValidation()) {
this.setState({ submitted: true });
const { Username, Password } = this.state;
if (Username && Password) {
response = JSON.stringify(userActions.login(Username, Password));
console.log(response);
if (response != null) {
errors["Error"] = "Invalid Username or Password";
this.setState({
errors: errors
});
}
}
}
}
handleValidation() {
let isValid = true;
let errors = {};
if (this.state.submitted === true && IsEmpty(this.state.Username)) {
errors["Username"] = "Username is required";
isValid = false;
}
if (this.state.submitted === true && IsEmpty(this.state.Password)) {
errors["Password"] = "Password is required";
isValid = false;
}
this.setState({
errors: errors
});
return isValid;
}
render() {
const { Username, Password, submitted, errors } = this.state;
//var errorMessage = loginErrorMessage;
return (
<LoginLayoutComponent>
<div className="panel panel-default">
<div className="panel-heading"></div>
<div className="panel-body" autoFocus={false}>
<form method="post" name="LoginForm" onSubmit={this.handleSubmit}>
<div className='form-group row'>
<input className='form-control' type="text" placeholder="Username" name="Username" value={Username} onChange={this.handleChange} autoFocus />
{!IsEmpty(errors.Username) && <p>{errors.Username}</p>}
</div>
<div className='form-group row' >
<Input className="form-control" type="Password" placeholder="Password" name="Password" value={Password} onChange={this.handleChange} />
{!IsEmpty(errors.Password) && <p>{errors.Password}</p>}
</div>
<Button className="btn btn-warning btn-block" onClick={this.handleSubmit}>Login</Button>
</form>
{!IsEmpty(errors.Response) && <p><b>Login Failed</b>.{errors.Response}</p>}
</div>
</div>
</LoginLayoutComponent>
);
}
}
function mapStateToProps(state) {
//const { loading } = state.authentication;
return {
// loginErrorMessage: state.authentication.error && state.authentication.error.message
};
}
const LoginForm = connect(mapStateToProps)(LoginFormComponent);
export { LoginForm };
=======================================================================
Action
import { history } from '../helpers/history';
import { userService } from '../services/user.service';
import { userConstants } from '../constants/user.constants';
export const userActions = {
login,
logout
};
function login(Username, Password) {
//return dispatch => {
console.log('Action begin');
userService.login(Username, Password)
.then(
results => {
if (results.username) {
console.log('success');
history.push('/home');
return { type: userConstants.LOGIN_SUCCESS, Username };
}
}, error => {
return { error };
}
);
//};
}
====================================================================
Service
import { HandleResponse, Logout } from '../helpers/utils';
export const userService = {
login,
logout,
_setUserSession
};
function login(Username, Password) {
const requestOptions = {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json; charset=utf-8'
}),
body: JSON.stringify({
Username,
Password
})
};
const requestPath = "http://localhost:53986/api/login/postlogin";
console.log('Start Fetching');
return fetch(requestPath,requestOptions)
.then(HandleResponse)
.then(response => {
var result = response && response.results && response.results.length > 0 ? response.results[0] : null;
if (result) {
console.log('Setting session');
_setUserSession(result);
}
return {result};
}).catch(function (error) {
return Promise.reject(error);
});
}
// Login successful :: store user details
function _setUserSession(user) {
if (user.id) {
localStorage.setItem('user', JSON.stringify(user));
}
}
===========================================
IsEmpty (As requested)
export function IsEmpty(param) {
return param === null || param === undefined || param === "" || (typeof param === "object" && param.length === 0) || param === false || param === 0;
}
Ожидаемый результат - отображение ошибки в ответе.и отобразить его в форме входа в систему для пользователя.