【问题标题】:then() method is executing before the data is actually returned in reactthen() 方法在反应中实际返回数据之前执行
【发布时间】:2019-02-14 02:27:25
【问题描述】:

请看下面的代码:

class WhiteBoard extends React.Component {
constructor(props) {
    super(props);
    this.userService = new UserService();
    this.state = {user: []};
}

userLogin = (user) => {
    console.log("inside whiteborad user login");

    let loginuser = {
        username: user.username,
        password: user.password
    };
    console.log(loginuser);

    this.userService.getLoggedInUser(loginuser)
        .then( data => {
            console.log("adsad"+mydata);
            this.setState({user: mydata})
        });

    console.log(this.state.user)
}

UserService 如下:

class UserService {

async getLoggedInUser(user){
    console.log("inside user service");
    console.log(user);
    const USER_API_URL = API_URL + "/api/login";
    fetch(USER_API_URL, {
        headers : {
            'Content-Type' : 'application/json'
        },
        method : "POST",
        body : JSON.stringify(user)
    }).then(response => response.clone().json()).then(data => {
        console.log(data);
        return data;
    });
}
}

export default UserService;

我在控制台中得到以下输出:

inside whiteborad user login
WhiteBoard.js:29 {username: "bird", password: "bird"}
UserService.js:6 inside user service
UserService.js:7 {username: "bird", password: "bird"}
WhiteBoard.js:37 []
WhiteBoard.js:33 adsadundefined
UserService.js:16 {id: 100, username: "bird", password: "bird", firstName: "Alice", lastName: "Kathie", …}

问题是,我在 userService.getLoggedInUser().then() 部分调用的 then 方法中得到了未定义的数据。因此,setState 不起作用并返回 null。 userService 方法中的数据非常好。但是,在 userLogin 方法中,当我调用 userService 时,该方法不等待从 userService 函数获取响应。我该如何解决这个问题?

【问题讨论】:

  • 需要返回调用fetch的结果; getLoggedInUser() 本身返回 undefined

标签: javascript reactjs


【解决方案1】:

问题是你使用了一个promise,但不要return它,所以调用者与它没有连接,而是你的then链接到async函数的默认promise。这里的正常解决方法是return fetch(...),但您可以采用另一种方法,因为您使用的是async 函数。

要修复它,请利用async 并使用await

class UserService {
  async getLoggedInUser(user){
    console.log("inside user service");
    console.log(user);
    const USER_API_URL = API_URL + "/api/login";

    let response = await fetch(USER_API_URL, {
        headers : {
            'Content-Type' : 'application/json'
        },
        method : "POST",
        body : JSON.stringify(user)
    });

    let data = await response.clone().json();

    console.log(data);
    return data;
  }
}

现在已经正确排序了。

在使用带有then 链接的承诺时,最常见的问题之一是丢球并忘记明确地return 承诺在继续之前需要等待。

【讨论】:

  • return fetch(USER_API_URL, {... 有用吗? (在函数声明中删除async 之后)
  • 没有必要删除async,但如果您不打算使用await,则需要删除return。你需要以某种方式将球向前推进。 async 函数可以返回承诺,在这种情况下它们会正确链接。
  • 谢谢,它确实解决了这个问题。我不知道这是问题所在。干杯!
猜你喜欢
  • 2014-07-13
  • 2021-05-15
  • 2013-06-03
  • 2019-02-22
  • 2017-06-07
  • 2019-08-01
  • 2020-08-15
  • 2018-02-08
  • 2021-01-06
相关资源
最近更新 更多