axios 每次我更改输入字段时,React都会将表单输入发送到后端

af7jpaap  于 2023-03-18  发布在  iOS
关注(0)|答案(2)|浏览(130)

我有一个函数可以向我的快速后端发送一个post请求

function postFood (foodName, foodType, foodDescription){
  Axios.post("http://localhost:3001/food", {
  foodName: foodName,
  foodType: foodType,
   foodDescription: foodDescription,
 }).then(() => {
   console.log("food created successfully" + foodName, foodType, foodDescription);
 });
};

这是我的React组件,它接受用户输入(foodName、foodType、foodDescription)并将它们存储在状态中,* 仅 * 在按提交按钮时将它们发送到我的后端,但每当我对任何输入字段进行更改时,它都会发送信息

import React, { useState } from "react";
import postFood from "./Services/createFood";

 function NewFood({ closeFoodForm }) {

 const [foodName, setfoodName] = useState("");
 const [foodType, setfoodType] = useState("Hamburger");
 const [foodDescription, setfoodDescription] = useState("");

   // this function gets called everytime i make a change to the input fields.
  postFood(foodName, foodType, foodDescription);

 return (
  <div className="CreateNewFood">
   <form id="foodForm" >
   
    <label>Name</label>
    <input
      onChange={e => {
        setfoodName(e.target.value);
      }}
      id="inputFoodName"
      name="foodName"
    ></input>

   
    <select id="inputFoodType" name="foodType"
      onChange={e => setfoodType(e.target.value)}>
      <option value="hamburger">Hamburger</option>
      <option value="pizza">Pizza</option>
      <option value="kebab">Kebab</option>
    </select>

    <label>Description</label>
    <textarea
      onChange={e => {
        setfoodDescription(e.target.value);
      }}
      id="inputFoodDescription"
      placeholder="big hamburger with double patties "
      name="foodDescription"
    ></textarea>
     
    //when i press this button i would like to submit the form
    <button type="Submit" value="Submit"  id="submitButton" onClick={postFood}>
      Create
    </button>
  </form>
</div>
);
}
m528fe3b

m528fe3b1#

每次重新渲染时都调用postFood。删除此命令:

// this function gets called everytime i make a change to the input fields.
postFood(foodName, foodType, foodDescription);

并按如下所示编辑<button />元素:

<button type="submit" id="submitButton" onClick={() => postFood(foodName, foodType, foodDescription)}>
   Create
</button>

注意:您可能不应该使用onClick,而是在<form />元素上使用onSubmit,并从提交按钮中删除onClick

blpfk2vs

blpfk2vs2#

像这样试试

<button type="Submit" value="Submit"  id="submitButton" onClick={() => postFood(foodName, foodType, foodDescription)}>
          Create
</button>

把绳子拿掉

postFood(foodName, foodType, foodDescription);

否则,状态的每次更改都会触发函数

相关问题