【发布时间】: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