[英]Post Conditional Data in ReactJs
so I want to add conditional statements in my POST method function in React.所以我想在 React 的 POST 方法 function 中添加条件语句。 I have a useState variable called empType that could be toggled by buttons to be set to "normal" or "others".
我有一个名为 empType 的 useState 变量,可以通过按钮将其切换为“正常”或“其他”。 I want to be able to exclude data2 from the JSON data that will be posted if empType is set to normal.
如果将 empType 设置为正常,我希望能够从将发布的 JSON 数据中排除 data2。 I tried using
{empType:== "normal" && data2: "something"}
but obviously its a syntax error.我尝试使用
{empType:== "normal" && data2: "something"}
但显然这是一个语法错误。
Here is my code这是我的代码
export default function App() {
const [empType, setEmpType] = useState("blank");
const onSubmit = () => {
fetch(`/apiendpoint`, {
method: "POST",
headers: { "Content-type": "application/json; charset=UTF-8" },
body: JSON.stringify({
data1: "something",
data2: "something"
})
})
.then((response) => response.json())
.then((message) => console.log(message))
.catch((error) => {
console.log(error);
});
};
return (
<div className="App">
<button onClick={() => setEmpType("normal")}>
set Emp type to normal
</button>
<br />
<button onClick={() => setEmpType("others")}>
set Emp type to others
</button>
<br />
Emp Type = {empType}
<br />
<button onClick={onSubmit}>submit</button>
</div>
);
}
I highly appreciate any help.我非常感谢任何帮助。 Thank you
谢谢
why not try building the data before the fetch call.为什么不尝试在获取调用之前构建数据。
const onSubmit = () => {
const data = {
data1: "something"
}
if (empType !== "normal") data.data2 = "something"
fetch(`/apiendpoint`, {
method: "POST",
headers: { "Content-type": "application/json; charset=UTF-8" },
body: JSON.stringify(data)
})
.then((response) => response.json())
.then((message) => console.log(message))
.catch((error) => {
console.log(error);
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.