簡體   English   中英

React 組件不呈現 Axios 請求的響應

[英]React component not rendering response of Axios request

我有一個表單輸入,允許用戶輸入文本並提交。 點擊提交按鈕后,我會通過檢查輸入是否為空或超過 120 個字符來驗證輸入。 我還將輸入傳遞給檢查語法並自動修復它的 API。

現在,我的 Axios 回復就在那里(我可以通過 console.log 記錄它),但在我的數據庫和其他地方,它是未更正的版本。


import React, { Component } from "react";
import axios from "axios";


class CreateText extends Component {

    constructor() {
        super();
        this.state = {
            textInput: "",
        };

    }

    checkGrammar = async () => {
        let response = await axios({
            method: 'get',
            url: 'https:/an-api-endpoint/',
            params: {
                apiKey: '',
                userId: '',
                content: this.state.textInput,
                format: 'json'
            }
        });
        const { data } = await response;
        // if I console log after this, I see it in my state as the correct version
        this.setState({
            textInput: data['corrected-content'] ? data['corrected-content'] : this.state.textInput
        });
    }


    handleInput = event => {
        this.setState({
            textInput: event.target.value
        });
    }

    handleSubmit = event => {
        event.preventDefault();

        this.validateInput();
        if (this.state.textInput) { 
          // push to db and clear the text state
            this.setState({
                textInput: ""
            });
        }
        else {
            console.log('Failed handle submit');
        }

    }

    validateInput = () => {
        if (this.state.textInput !== "") {
            if (this.state.textInput.length < 120) {
                this.checkGrammar();
            }
            else {
                console.log('Failed validate input');
                return; // TODO: Error handling.
            }
        }
    }

    render() {
        return (
            <div className="input">
                <form onSubmit={this.handleSubmit}>
                    <label htmlFor="textInput"></label>
                    <input
                        id="textInput"
                        type="text"
                        value={this.state.textInput}
                        onChange={this.handleInput}
                        placeholder="insert text"
                    />
                    <button className="textButton" type="submit">Submit Text</button>
                </form>
            </div>
        )
    }
}

export default CreateText;

我嘗試setState來為textInput為響應異步使用/ AWAIT,我嘗試過其他方法,但似乎當我點擊提交/ handleSubmit ,它調用該API,而是繼續並提交,然后得到校正輸入。 之后我可以在我的文本輸入中看到它,這不應該發生,因為提交后,狀態文本被清除。 它讓我相信它被添加、清除,然后 axios 數據返回並填充狀態(為時已晚。)

我在這里做錯了什么嗎? 我對 axios 承諾感到困惑,並認為我可以使用 setState 和 async/await 來處理它。

謝謝。

您可以像這樣移動 checkGrammar 函數中的 textInput 條件邏輯以避免異步競爭條件:

import React, { Component } from "react";
import axios from "axios";


class CreateText extends Component {

    constructor() {
        super();
        this.state = {
            textInput: "",
        };

    }

    checkGrammar = async () => {
        let response = await axios({
            method: 'get',
            url: 'https:/an-api-endpoint/',
            params: {
                apiKey: '',
                userId: '',
                content: this.state.textInput,
                format: 'json'
            }
        });
        const { data } = response;
        // if I console log after this, I see it in my state as the correct version
        const textInput = data['corrected-content'] ? data['corrected-content'] : this.state.textInput;
        if ( textInput ) { 
            // push to db and clear the text state
              this.setState({
                  textInput: ""
              });
          }
          else {
              console.log('Failed handle submit');
          }

    }


    handleInput = event => {
        this.setState({
            textInput: event.target.value
        });
    }

    handleSubmit = event => {
        event.preventDefault();
        this.validateInput();
    }

    validateInput = () => {
        if (this.state.textInput !== "") {
            if (this.state.textInput.length < 120) {
                this.checkGrammar();
            }
            else {
                console.log('Failed validate input');
                return; // TODO: Error handling.
            }
        }
    }

    render() {
        return (
            <div className="input">
                <form onSubmit={this.handleSubmit}>
                    <label htmlFor="textInput"></label>
                    <input
                        id="textInput"
                        type="text"
                        value={this.state.textInput}
                        onChange={this.handleInput}
                        placeholder="insert text"
                    />
                    <button className="textButton" type="submit">Submit Text</button>
                </form>
            </div>
        )
    }
}

export default CreateText;

代碼沙盒

建議:您絕對應該閱讀更多關於異步函數(如setState )如何工作的內容,並嘗試了解 async/await,因為 JavaScript/React 中每天都會出現此類問題。

如果您打算使用 React,您必須了解異步setState方法的內部工作原理,並了解該方法的回調版本。 這個StackOverflow 帖子是一個很好的起點。

從帖子中,這可能是最關鍵的一點:“ setState異步方式工作。這意味着在調用setStatethis.state變量不會立即更改。因此,如果您想在對狀態設置狀態后立即執行操作變量然后返回一個結果,回調將是有用的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM