微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在ReactJS中将属性从一个函数传递给另一个函数

如何解决如何在ReactJS中将属性从一个函数传递给另一个函数

我正在尝试从功能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)},)
  }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。