在 React 中使用 Async/Await 进行 API 响应

Posted

技术标签:

【中文标题】在 React 中使用 Async/Await 进行 API 响应【英文标题】:Using Async/Await In React for API Response 【发布时间】:2020-11-12 18:18:43 【问题描述】:

所以基本上,API 将根据用户输入发回 true/false 的响应,我正在尝试将变量 res 设置为该响应,以便我可以使用它来呈现下一个组件。但是,我需要等到响应实际返回,否则该值将是错误的,因为它在实际通过之前运行axios 帖子下方的代码。所以我决定使用async/await 但由于某种原因它现在正在重新加载原始表单 ApplyForm?当我取出 async 并等待它并没有这样做时,我很困惑。有人可以帮助找出问题或提出另一种方法吗?感谢任何帮助。

ApplyForm.js

    import React from "react";
    import Component from "react";
    import ReactDOM from 'react-dom';
    import PaymentForm from './PaymentForm.js'

    class ApplyForm extends React.Component 
      constructor(props) 
          super(props);
          this.state = providerID: ''
      

      handleSubmit = (e) => 
      ReactDOM.render(<PaymentForm data = this.state.providerID />, document.getElementById('root'));
    

    onChange = (e) => 
       this.setState(
         providerID: e.target.value,
       );
     

     shouldComponentUpdate() 
        return false;
     

    render() 
      return (
        <form onSubmit=this.handleSubmit>
        <h1> Apply for a payment plan </h1>
        <p>Four Letter Provider ID:</p>
        <input
          type='text'
          name = "providerID"
          onChange=this.onChange
        />
        <br></br>
        <small> If you do not have a provider ID, you can skip this part. </small>
        <p>Payment Plan Amount:</p>
        <input
          type='number'
          required
          onChange=this.myChangeHandler
        />
         <p>Your Procedure:</p>
         <input
           type='text'
           name = "Procedure"
           required
           onChange=this.myChangeHandler
        />
        <br></br>
        <br></br>
        <input type="button" value="Submit" onClick=this.handleSubmit/>
        </form>
      );
    
      

    export default ApplyForm;

PaymentForm.js

    import React from "react";
    import Component from "react";
    import ReactDOM from 'react-dom';
    import Link from './Link.js';
    import axios from 'axios'
    let res = false;

    class PaymentForm extends React.Component 
      constructor(props) 
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.state = provID: this.props.data;
     

      async handleSubmit(event) 
      const data = new FormData(event.target);
      const res = await axios(
        method: 'post',
        url: 'test-url',
        data: 
            httpMethod: "POST",
            body: 
                UID: "123456",
                Last_Name: data.get('Last_Name'),
                personal_data: 
                    Treatment_Plan: data.get('Plan'),
                    First_Name: data.get('First_Name'),
                    Last_Name: data.get('Last_Name'),
                    Address: data.get('Address'),
                    Unit: data.get('Unit'),
                    City: data.get('City'),
                    State: data.get('State'),
                    Zip: data.get('Zip'),
                    Email: data.get('Email'),
                    Employment_status: data.get('Employment_status'),
                    EST_Credit: data.get('EST_Credit'),
                    Phone: data.get('Phone'),
                    DOB: data.get('DOB'),
                    Income: data.get('Income'),
                    Rent: data.get('Rent'),
                    SSN: data.get('SSN'),
                    Co_App: data.get('Test'),
                ,
                provider_data: 
                    Provider_ID: this.state.provID,
                    Procedure_Amount: data.get('Request_Amount'),
                    Procedure_Des: data.get('Loan_Purpose')
                ,
            
        
      ).then((response) => 
          res = response['data']['is_passed'];
          console.log(res);
      );

      if (res) 
        ReactDOM.render(<Link />, document.getElementById('root'));
      

    

    render() 
      return (
        <form onSubmit=this.handleSubmit>
        <h1> See Your Loan Options </h1>
        <p>Request $1000 to $100000</p>
        <input
            type='Number'
            name = "Request_Amount"
            onChange=this.myChangeHandler
        />
        <br></br>

        <p>Loan Purpose:</p>
        <input
            type='text'
            name = "Loan_Purpose"
            required
            onChange=this.myChangeHandler
        />

         <p>Do you already have a treatment plan for your procedure?</p>
         <input type="radio" id="Yes" value = "Yes" name = "Plan" onChange=this.myChangeHandler/>
         <label for="Yes">Yes</label>
         <input type="radio" id="No" value = "No" name = "Plan" onChange=this.myChangeHandler/>
         <label for="Yes">No</label>
        <br></br>

        <p>What is the name of your provider?</p>
            <input type='text' name = "Provider" required onChange=this.myChangeHandler/>
            <br></br>
            <br></br>

         <p>First Name</p>
            <input type='text' name = "First_Name" required onChange=this.myChangeHandler/>
            <br></br>
            <br></br>

         <p>Last Name</p>
            <input type='text' name = "Last_Name" required onChange=this.myChangeHandler/>
            <br></br>
            <br></br>

         <p>Street Address</p>
            <input type='text' name = "Address" required onChange=this.myChangeHandler/>
            <br></br>
            <br></br>

         <p>Unit Number</p>
            <input type='text' name = "Unit_Number" onChange=this.myChangeHandler/>
            <br></br>
            <br></br>

         <p>City</p>
            <input type='text' name = "City"  required onChange=this.myChangeHandler/>
            <br></br>
            <br></br>

         <p>State</p>
            <select name = "State" >
            <option value="" selected disabled hidden>State</option>
                <option value="AL">Alabama</option>
                <option value="AK">Alaska</option>
                <option value="AZ">Arizona</option>
                <option value="AR">Arkansas</option>
                <option value="CA">California</option>
                <option value="CO">Colorado</option>
                <option value="CT">Connecticut</option>
                <option value="DE">Delaware</option>
                <option value="DC">District Of Columbia</option>
                <option value="FL">Florida</option>
                <option value="GA">Georgia</option>
                <option value="HI">Hawaii</option>
                <option value="ID">Idaho</option>
                <option value="IL">Illinois</option>
                <option value="IN">Indiana</option>
                <option value="IA">Iowa</option>
                <option value="KS">Kansas</option>
                <option value="KY">Kentucky</option>
                <option value="LA">Louisiana</option>
                <option value="ME">Maine</option>
                <option value="MD">Maryland</option>
                <option value="MA">Massachusetts</option>
                <option value="MI">Michigan</option>
                <option value="MN">Minnesota</option>
                <option value="MS">Mississippi</option>
                <option value="MO">Missouri</option>
                <option value="MT">Montana</option>
                <option value="NE">Nebraska</option>
                <option value="NV">Nevada</option>
                <option value="NH">New Hampshire</option>
                <option value="NJ">New Jersey</option>
                <option value="NM">New Mexico</option>
                <option value="NY">New York</option>
                <option value="NC">North Carolina</option>
                <option value="ND">North Dakota</option>
                <option value="OH">Ohio</option>
                <option value="OK">Oklahoma</option>
                <option value="OR">Oregon</option>
                <option value="PA">Pennsylvania</option>
                <option value="RI">Rhode Island</option>
                <option value="SC">South Carolina</option>
                <option value="SD">South Dakota</option>
                <option value="TN">Tennessee</option>
                <option value="TX">Texas</option>
                <option value="UT">Utah</option>
                <option value="VT">Vermont</option>
                <option value="VA">Virginia</option>
                <option value="WA">Washington</option>
                <option value="WV">West Virginia</option>
                <option value="WI">Wisconsin</option>
                <option value="WY">Wyoming</option>
            </select>
            <br></br>
            <br></br>

         <p>Zip Code</p>
            <input type='text' name = "Zip" required onChange=this.myChangeHandler/>
            <br></br>
            <br></br>

         <p>Email Address</p>
            <input type='email' name = "Email" required onChange=this.myChangeHandler/>
            <br></br>
            <br></br>

            <p>Confirm Email Address</p>
            <input type='email' required onChange=this.myChangeHandler/>
            <br></br>
            <br></br>

         <select name = "Employment_status" >
            <option value="" selected disabled hidden>Employment Status</option>
            <option value="E">Employed</option>
            <option value="U">Unemployed</option>
            <option value="S">Self Employed</option>
            <option value="M">Military</option>
            <option value="R">Retired Benefits</option>
            <option value="O">Other</option>
          </select>
          <br></br>
          <br></br>

          <select name = "EST_Credit" >
            <option value="" selected disabled hidden>Estimated Credit Range</option>
            <option value="E"> > 720</option>
            <option value="U">680 - 720</option>
            <option value="S">640 - 679</option>
            <option value="M">550 - 639</option>
            <option value="R"> &#60; 550 </option>
          </select>
          <br></br>
          <br></br>

         <p>Mobile</p>
            <input type='text' name = "Phone" required onChange=this.myChangeHandler/>
            <br></br>
            <br></br>

         <p>Date of Birth (yyyy/dd/mm)</p>
            <input type='text' name = "DOB" required onChange=this.myChangeHandler/>
            <br></br>
            <br></br>

         <p>Annual Individual Income</p>
            <input type='text' name = "Income" required onChange=this.myChangeHandler/>
            <br></br>
            <br></br>

            <select name = "Rent" >
            <option value="" selected disabled hidden>Housing Status</option>
            <option value="E">Rent</option>
            <option value="U">Mortgage</option>
            <option value="S">Fully-Owned</option>
            <option value="M">Partially-Owned</option>
            <option value="R">Other</option>
          </select>
          <br></br>
          <br></br>

          <p>Social Security Number</p>
            <input type = "password" name = "SSN"  required onChange=this.myChangeHandler/>
            <br></br>
            <br></br>

          <p>Confirm Social Security Number</p>
            <input type = "password" required onChange=this.myChangeHandler/>
            <br></br>
            <br></br>

         <p>Do you want to add a co-applicant?</p>
         <input type="radio" id="Yes" value = "Yes" name = "Test" onChange=this.myChangeHandler/>
          <label for="Yes">Yes</label>
          <input type="radio" id="No" value = "No" name = "Test" onChange=this.myChangeHandler/>
          <label for="Yes">No</label>
        <br></br>
        <br></br>

        <input type="checkbox" required id="Agree"/>
        <label for = "Agree"> Our Terms of Use, Privacy Policy, Credit Report Authorization and Telephone and Email Consents.</label>
        <br></br>
        <br></br>

        <button>See My Rates</button>
        </form>
      );
    
  

export default PaymentForm;

【问题讨论】:

您需要在表单提交处理程序上e.preventDefault() 以防止表单的默认行为(提交重新加载它的页面) 您能进一步解释一下吗?在哪个提交处理程序中?谢谢 你有一个表格。 &lt;form onSubmit=this.handleSubmit&gt;。当表单提交时,它的默认行为是将页面发布到服务器,服务器也会刷新页面,因为通常服务器会返回一个新页面来呈现。在做单页申请的时候,不希望表单实际提交页面,所以需要防止这种行为。函数handleSubmit 接受您别名为e 的提交事件。所以你需要在handleSubmit 函数的第一行添加e.preventDefault()。我建议你阅读form submission 【参考方案1】:

如果您已经在使用 Promise,则无需再次使用 async-awaitasync-await 是 Promise 的另一种语法。

您的代码的问题是您需要在承诺解决后进行重定向。

你只需要像这样在.then方法中移动重定向部分。

    const res = axios(
    method: 'post',
    url: 'test-url',
    data: 
        httpMethod: "POST",
        body: 
            UID: "123456",
            Last_Name: data.get('Last_Name'),
            personal_data: 
                Treatment_Plan: data.get('Plan'),
                First_Name: data.get('First_Name'),
                Last_Name: data.get('Last_Name'),
                Address: data.get('Address'),
                Unit: data.get('Unit'),
                City: data.get('City'),
                State: data.get('State'),
                Zip: data.get('Zip'),
                Email: data.get('Email'),
                Employment_status: data.get('Employment_status'),
                EST_Credit: data.get('EST_Credit'),
                Phone: data.get('Phone'),
                DOB: data.get('DOB'),
                Income: data.get('Income'),
                Rent: data.get('Rent'),
                SSN: data.get('SSN'),
                Co_App: data.get('Test'),
            ,
            provider_data: 
                Provider_ID: this.state.provID,
                Procedure_Amount: data.get('Request_Amount'),
                Procedure_Des: data.get('Loan_Purpose')
            ,
        
    
  ).then((response) => 
      res = response['data']['is_passed'];
      console.log(res);
      if (res) 
        ReactDOM.render(<Link />, document.getElementById('root'));
     
  );

【讨论】:

我试过了,它出于某种原因重新加载了原始组件。和我的问题评论的原因一样吗? 你是否删除了异步等待并尝试

以上是关于在 React 中使用 Async/Await 进行 API 响应的主要内容,如果未能解决你的问题,请参考以下文章

在 ES6 React .JS 中使用 Async/Await

在 React Native 中使用 async/await 处理 API 调用

如何在 React 中使用 useEffect hook 和 async/await 检索嵌套的 JSON 数据

如何在 React (async/await) 中创建一个原子进程?

如何使用 Async / Await 和 React 钩子?

为啥 Async Await 可以与 React setState 一起使用?