- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个表单输入,允许用户输入文本并提交。点击提交按钮后,我通过检查输入是否为空或是否超过 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;
建议:您绝对应该阅读更多有关异步函数(如 setState
)如何工作的内容,并尝试理解 async/await,因为这些问题会出现每天使用 JavaScript/React。
如果您打算使用 React,则必须了解异步 setState
方法的内部工作原理,并了解此方法的回调版本。这是一个很好的起点 StackOverflow post .
从帖子来看,这可能是最关键的一点:“setState
以异步方式工作。这意味着在调用 setState
this.state
变量不会立即改变。所以如果你想在状态变量上设置状态后立即执行一个 Action ,然后返回一个结果,一个回调会有用的"
关于javascript - React 组件不呈现 Axios 请求的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59111822/
我有一个 axios 拦截器,我在其中捕获 401 错误并将用户重定向到登录页面。问题是在 window.location 运行之后和实际重定向之前 - axios 操作继续到原始调用者。我想停止进程
我正在调用一个返回至少 2 个成功状态代码的 Rest API。 正常的 200 OK 和 202 Accepted 状态代码。 两者都在正文中返回一个内容。 如果我在 postman 中执行我的电话
任何人都可以提出任何从 Axios 获得响应时间的方法吗?我找到了 axios-timing,但我真的不喜欢它(有争议,我知道)。我只是想知道是否有人找到了一些记录响应时间的好方法。 最佳答案 您可以
我正在尝试使用 axios.create() 创建一个 axios 实例但似乎无法弄清楚如何在实例上设置默认方法。 不工作 export default axios.create({ requ
我正在将 axios 用于 React 应用程序,并且我想记录我在应用程序中任何位置进行的所有 axios 调用。我已经通过 create 函数使用了 axios 的单个全局实例,并且我能够记录通用的
我有一个公开一些端点的 NestJS 应用程序,我已经编写了一个客户端应用程序,我计划将其作为 NPM 包发布以与 nest 服务器一起使用。我正在尝试编写启动 nest 服务器的端到端测试,将其连接
我一直在使用这个将图像文件上传到 API (Graphcool),并且一切正常: fileUpload(file) { let data = new FormData();
在我的代码库中有使用创建的各种 Axios 实例 axios.create() 因为我的应用程序中使用了多个基本 URL。所以每个 baseURL 我们都创建了一个对应的 Axios 实例。 现在在
我有一个 API 实用程序函数,它使用构造函数符号调用 axios: axios({ method, url: `${BASE_URL}/${url}`, data }); 我想用
我正在尝试使用 mockAxios 来测试 axios 拦截器。 export default { get: jest.fn(() => Promise.resolve({ data: {}
https://github.com/axios/axios#cancellation 我正在研究如何取消上传 PUT 请求并在文档中遇到了这一部分。为什么需要 token 才能取消?简单来说流程或过
axios.put('http://localhost:3000/api/userDatas/findUserAddProp',{ params: { userId: "5bb
我的 axios promise 没有按预期工作。我猜执行是在 forEach 循环内开始的。我希望 axios 执行仅在 batch.commit 之后开始 aMobileNumbers.forEa
有区别吗 useEffect(()=>{ async function fetchData(){ await axios .get(path, config) .t
我正在使用 axios 获取信息,并且我需要在不同 axios 响应的另一个处理程序中使用该信息。我似乎无法在第二个响应处理中使用第一个响应中加载的数据。 例如: const [firstData,
我在我的 React 应用程序中使用 axios,在我的许多脚本中使用 import axios from 'axios 。我想使用一种为所有 axios 调用/错误调用的中间件。我该如何处理这个问题
在我的应用程序中,为了对用户进行身份验证,我调用了 fetchData 函数。如果用户 token 无效,应用程序将运行 axios.all(),我的拦截器将返回大量错误。 如何防止 axios.al
我已经按照 npm 包文档中的建议编写了一个 Axios POST 请求,例如: var data = { 'key1': 'val1', 'key2': 'val2' } axios
谁能提供有关 axios 和 vue-axios 之间区别的详细信息?我们需要使用哪一个?两者都需要使用api吗? 谢谢 最佳答案 vue-axios 只是一个包装器,将 axios 暴露给组件作为
我在向 Loopback(v3) API 发出的 Axios 请求中使用变量时遇到了麻烦。 什么有效?如果我使用“REST 表示法”,它运行良好: getInfo() { axios.get(
我是一名优秀的程序员,十分优秀!