我有一个函数可以向我的快速后端发送一个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>
);
}
2条答案
按热度按时间m528fe3b1#
每次重新渲染时都调用
postFood
。删除此命令:并按如下所示编辑
<button />
元素:注意:您可能不应该使用
onClick
,而是在<form />
元素上使用onSubmit
,并从提交按钮中删除onClick
。blpfk2vs2#
像这样试试
把绳子拿掉
否则,状态的每次更改都会触发函数