首页 > 解决方案 > 点击按钮提交后,它调用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 次,如何解决此问题? 在此处输入图像描述

标签: javascriptreactjs

解决方案


祝你有美好的一天,我想你可以试试这个:

   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>
    );
  }
}

也许您想在发送数据时显示加载器,因此控制该加载器的状态以及用户是否可以发送请求是一个好方法,我希望对您有所帮助


推荐阅读