Я пытаюсь прочитать значение вызова axios.get() в переменной флага (вывод либо истина, либо ложь).
Я создаю приложение springboot + reactjs.
Требование этого кода / Требуемый поток кода:
Step 1 : enter username and password
Step 2 : On click of button submit it should call handleChangeEvent() method
Step 3 : In the handle change method it should call the callFunction() method.
Step 4 : it should get the data from server and then move to the "THEN BLOCK" where response is printed in console and an alert is given next and then the value is returned to handle change method after which another alert is given . But in step 4 the "THEN BLOCK" is not executed and it just jumps so value in handleChangeEvent() method is undefined . But after whole process is done at last the THEN block is executed.
Можете ли вы сказать, в чем проблема и что мне не хватает? Мне нужен вывод как:
1.response.Data( which is either true or false which i recieve from get http call) in console
2.alert box showing the response.data
Return value
In console -> response.data(true or false) is the response
5.alert ( you have entered username: shaik and password : ****)
Текущий выходной сигнал, который я получаю:
1.In console -> "undefined" is the response
2.alert ( you have entered username: shaik and password : ****)
3.response.Data( which is either true or false which i recieve from get http call) in console
4.alert box showing the response.data
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
class Login extends Component {
constructor(props) {
super(props);
this.state = {
userName: '',
password: ''
};
this.updateState = this.updateState.bind(this);
this.handleChangeEvent = this.handleChangeEvent.bind(this);
this.callFuction = this.callFuction.bind(this);
}
updateState(e) {
this.setState({
[e.target.name]: e.target.value
});
}
handleChangeEvent = (event) => {
debugger;
var flag = this.callFuction();
console.info(flag +"is the response")
alert("You have entered : \n User Name :" + this.state.userName + " \n Password :" + this.state.password);
event.preventDefault();
}
callFuction(){
debugger;
axios.get('http://localhost:8086/login/check?userName='+this.state.userName+'&password='+this.state.password ).then(response => {
debugger;
console.info(response.data);
alert(response.data);
return response.data;
});
}
render() {
return (
<form >
<label>User Name:
<input type = "text" name = "userName" onChange = {this.updateState} />
</label>
<label>Password:
<input type = "password" name = "password" onChange = {this.updateState} />
</label>
<input type = "submit" value = "Submit" onClick = {this.handleChangeEvent} />
</form>
)
}
}
export default Login;





Вы получаете undefined, потому что вы ничего не возвращаете с вашего callFunction, вы должны вернуть результат axios get, но он вернет обещание, поэтому вы должны установить флаг после разрешения promise.
Вот небольшой пример:
handleChangeEvent = (event) => {
this.callFunction()
.then(flag => {
console.info(flag +" is the response")
alert("You have entered : \n User Name :" + this.state.userName + " \n Password :" + this.state.password);
});
event.preventDefault();
}
callFuction(){
return axios.get('http://localhost:8086/login/check?userName='+this.state.userName+'&password='+this.state.password ).then(response => {
return response.data;
});
}
Вкратце процесс выглядит следующим образом: 1. нажмите кнопку -> this.callFunction () -> он выполняет итерацию http-запроса, но затем не переходит в метод, в котором присутствует return response.data -> он выходит из функции и переходит вернемся к this.callFunction () -> здесь он снова не входит в цикл then (). Цикл response.data и then () повторяется снова позже. Как это происходит ... Я - backend-разработчик, поэтому я использую пошаговый процесс, поэтому я немного запутался здесь
Потому что, если вы не вернете axios.get. обещание, вы получите undefined, потому что вы ничего не возвращаете в этой функции.
Если я добавлю окно предупреждения вне блока callFunction (), оно будет выполнено первым, а затем будет выполнено консольное значение в блоке callFunction (). Разве это не неправильный поток?
Спасибо, это сработало, но не так, как я ожидал. Можете ли вы сказать мне, почему нам нужно дважды добавить оператор return в метод callFunction (), а также относительно того, когда я вызываю handlechange (), поток отличается, «return response.data» снова повторяется позже.