首页 > 解决方案 > 获取显示值但无法将其保存到变量的控制台

问题描述

这就是我所拥有的。

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 个字符串,成功或失败。日志将显示成功,但由于某种原因,我无法将其分配给变量。

标签: javascriptreactjsapifetch

解决方案


您正在内部发出异步请求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-awaitlike

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);
}

推荐阅读