问题描述
我正在尝试从功能getFirstApi()获取用户的电子邮件,并将其传递给getSecondApit(),以便可以将其用作fetch()请求中的参数。
我的代码:
getFirstApi() {
Auth.currentAuthenticatedUser().then((user) => {
this.setState({email: user.attributes.email,formemail: user.attributes.email})
return email
});
}
getSecondApi() {
fetch(`https://ezha2ns0bl.execute-api.ap-southeast-2.amazonaws.com/prod/userdata?foo=${encodeURIComponent(email)}`)
.then(res => res.json())
.then(
console.log("THIS IS RESULT" + email),(result) => {
this.setState({
firstname: result.Item.userFirstName,middlename: result.Item.userMiddleName,surname: result.Item.userLastName,city: result.Item.userCity,postcode: result.Item.userPostcode,state: result.Item.userState,about: result.Item.userAbout,formfirstname: result.Item.userFirstName,formmiddlename: result.Item.userMiddleName,formsurname: result.Item.userLastName,formcity: result.Item.userCity,formpostcode: result.postcode,formstate: result.Item.userState,formabout: result.Item.userAbout,});
console.log("THIS IS RESULT" + result)},)
}
我的componentDidMount
componentDidMount() {
this.getFirstApi();
this.getSecondApi();
}
此url api调用可在我的浏览器中使用,所以我认为它是我需要的。
https://ezha2ns0bl.execute-api.ap-southeast-2.amazonaws.com/prod/userdata?userEmail=%22gitigol723@hapremx.com%22
解决方法
您应确保返回第一个API调用的Promise
。然后,您可以在完成后使用它的结果。
// Where you call your APIs:
getFirstApi().then(email => {
getSecondApi(email);
});
// Return the API Promise in the first API
getFirstApi() {
// notice the 'return' statement here
return Auth.currentAuthenticatedUser().then((user) => {
this.setState({email: user.attributes.email,formemail: user.attributes.email})
return email
});
}
// add the email parameter to the method signature
getSecondApi(email) {
fetch(`https://ezha2ns0bl.execute-api.ap-southeast-2.amazonaws.com/prod/userdata?foo=${encodeURIComponent(email)}`)
.then(res => res.json())
.then(
console.log("THIS IS RESULT" + email),(result) => {
this.setState({
firstname: result.Item.userFirstName,middlename: result.Item.userMiddleName,surname: result.Item.userLastName,city: result.Item.userCity,postcode: result.Item.userPostcode,state: result.Item.userState,about: result.Item.userAbout,formfirstname: result.Item.userFirstName,formmiddlename: result.Item.userMiddleName,formsurname: result.Item.userLastName,formcity: result.Item.userCity,formpostcode: result.postcode,formstate: result.Item.userState,formabout: result.Item.userAbout,});
console.log("THIS IS RESULT" + result)},)
}