javascript - 点击按钮提交后,它调用API,它被触发2次的问题
问题描述
import React, { Component } from 'react';
import axios from "axios";
class User extends Component {
handleSubmit = (e, firstName, lastName) => {
e.stopPropagation();
e.preventDefault()
const start = Date.now()
axios.post('http://localhost:4000/api/user', {
params: {
firstName,
lastName
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
render(){
return (
<Button onClick={(e) => this.handleSubmit(e,firstname,lastname)}>submit</Button>
)}
}
我使用 nodejs 创建 API,命名/user
为 post 方法。
我尝试使用 reactjs 使用它,当按下按钮提交并检查以查看网络中发生了什么,它调用了 2 次,如何解决此问题? 在此处输入图像描述
解决方案
祝你有美好的一天,我想你可以试试这个:
class User extends Component {
constructor(props){
super(props)
this.state={
sendingData:false
}
this.toggleSendingData= this.toggleSendingData.bind(this);
}
toggleSendingData(){
this.setState({sendingData: !this.state.sendingData})
}
handleSubmit = (e, firstName, lastName) => {
e.stopPropagation();
e.preventDefault();
const start = Date.now();
if(this.state.sendingData) return;
this.toggleSendingData()
axios
.post("http://localhost:4000/api/user", {
params: {
firstName,
lastName,
},
})
.then(function (response) {
console.log(response);
this.toggleSendingData()
})
.catch(function (error) {
console.log(error);
this.toggleSendingData()
});
};
render() {
return (
<Button onClick={(e) => this.handleSubmit(e, firstname, lastname)}>
submit
</Button>
);
}
}
也许您想在发送数据时显示加载器,因此控制该加载器的状态以及用户是否可以发送请求是一个好方法,我希望对您有所帮助
推荐阅读
- mysql - 连接条件后无法使用 WHERE 子句过滤掉数据
- caching - zeromq: ZMQ_CONFLATE==1 不会阻止队列保存旧消息
- mysql - 分析时发现导入数据库错误
- kendo-ui - 剑道网格编辑事件处理程序不更新行
- python - 如果它是分类变量,如何替换空值?
- python - 我如何在 Python 中重构 Sconstruct 以使用 pycharm 检测可能的错误
- elasticsearch - Kibana 仪表板数据未显示
- python - Pyinstaller 无法识别 Nornir 并且脚本崩溃
- c# - C# Serial.read 正确读取字符,即使 BaudRate 错误
- regex - 将变量作为正则表达式环视的表达式传递