gpt4 book ai didi

javascript - React 组件不呈现 Axios 请求的响应

转载 作者:行者123 更新时间:2023-11-30 13:46:59 24 4
gpt4 key购买 nike

我有一个表单输入,允许用户输入文本并提交。点击提交按钮后,我通过检查输入是否为空或是否超过 120 个字符来验证输入。我还将输入传递给检查语法并自动修复它的 API。

现在,我的 Axios 回复就在那里(我可以控制台记录它),但在我的数据库和其他地方它是未更正的版本。


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;

我尝试使用 async/await 将 setState 设置为 textInput 以获取响应,我尝试了其他方法,但似乎当我点击 Submit/handleSubmit 时,它会调用到 API,但继续并提交,然后获取更正的输入。之后我可以在我的文本输入中看到它,这是不应该发生的,因为在提交后,状态文本被清除。这让我相信它被添加、清除,然后 axios 数据返回并填充状态(为时已晚。)

我在这里做错了什么吗?我对 axios promise 感到困惑,并认为我可以使用 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;

Codesandbox

建议:您绝对应该阅读更多有关异步函数(如 setState)如何工作的内容,并尝试理解 async/await,因为这些问题会出现每天使用 JavaScript/React。

如果您打算使用 React,则必须了解异步 setState 方法的内部工作原理,并了解此方法的回调版本。这是一个很好的起点 StackOverflow post .

从帖子来看,这可能是最关键的一点:“setState异步方式工作。这意味着在调用 setState this.state 变量不会立即改变。所以如果你想在状态变量上设置状态后立即执行一个 Action ,然后返回一个结果,一个回调会有用的"

关于javascript - React 组件不呈现 Axios 请求的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59111822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com