javascript - 获取显示值但无法将其保存到变量的控制台
问题描述
这就是我所拥有的。
var a;
handleSubmit(event) {
var a ;
event.preventDefault();
this.setState({username:'poop'})
console.log("submit");
fetch('http://localhost:8080/login/'+this.state.username+'/'+this.state.password,{
method: 'GET',
}).then((resp)=> resp.text())
.then(resp => {
console.log(resp)
a = resp;
});
console.log(a);
我的问题是 console.log(resp) 将记录我需要的正确值(“成功”),但是当我尝试执行 var a = resp 时,它显示为未定义。我的 api 返回 1 个字符串,成功或失败。日志将显示成功,但由于某种原因,我无法将其分配给变量。
解决方案
您正在内部发出异步请求handleSubmit
,因此您不会在 fetch Request 以您尝试访问它的方式后立即获得结果,您可以使用将结果存储在状态中setState
并在其他地方访问它this.state.data
handleSubmit(event) {
event.preventDefault();
this.setState({username:'poop'})
console.log("submit");
fetch('http://localhost:8080/login/'+this.state.username+'/'+this.state.password,{
method: 'GET',
}).then((resp)=> resp.text())
.then(resp => {
console.log(resp)
this.setState({data: resp});
});
}
或者,您可以使用async-await
like
async handleSubmit(event) {
event.preventDefault();
this.setState({username:'poop'})
console.log("submit");
const a = await fetch('http://localhost:8080/login/'+this.state.username+'/'+this.state.password,{
method: 'GET',
}).then((resp)=> resp.text())
console.log(a);
}
推荐阅读
- excel - 将单行数据转移到单列
- java - Apache CSV 解析器:忽略空行的问题
- react-native - React-navigation-redux-helpers 错误:此导航器同时具有导航和容器道具,因此不清楚它是否应该拥有自己的状态
- c# - 没有错误的条件匹配强制匹配?
- apache-kafka - kafka客户端是连接zookeeper还是在幕后
- javascript - 如何根据条件在数组中添加对象元素
- java - 在 JScape 中添加第二个域时出错
- javascript - 手机缝隙HTML5打不开摄像头
- javascript - 为什么间隔函数不执行,除非在Javascript中删除for循环
- android - 首次登录后尝试在我的 android 应用程序中保持用户登录但无法正常工作