I have here a code using React.js, this code returns undefined in the console..
getTicket = async() =>{
var ticketData;
this.state.client.get('ticket').then(
await function(data){
ticketData = data['ticket'].toString();
console.log(data['ticket'])
}
)
await this.setState({ ticketInformation: ticketData })
}
while this one is javascript, this code returns the value of ticketData..
var ticketData;
client.get('ticket').then(
function(data) {
ticketData = data['ticket'];
console.log("TICKET:: " + JSON.stringify(ticketData.id));
}
);
my question is, what is the difference between the 2? on the first code as you can see, I am using a async/await which should not return undefined as far as I know.. Somehow the 2nd code has no async/await but fully giving a value to the global variable.
I guess that's because when you first call getTicket function, this.state.client is undefined. You should give it a value as default first but in my knowledge, it's not good to give function to a "state". You should make the convert value function as a call back outside, not in "state" cuz React re-make the function again whenever the state value change and it wastes memory.
Try it as following, I hope you gain a goal.
await this.state.client.get('ticket').then(
function(data){
ticketData = data['ticket'].toString();
console.log(data['ticket'])
}
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.