所以我想在 React 的 POST 方法函式中添加條件陳述句。我有一個名為 empType 的 useState 變數,可以通過按鈕將其切換為“正常”或“其他”。如果 empType 設定為正常,我希望能夠從將發布的 JSON 資料中排除 data2。我嘗試使用{empType !== "normal" && data2: "something"},但顯然它是一個語法錯誤。
這是我的代碼
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>
);
}
我非常感謝任何幫助。謝謝
uj5u.com熱心網友回復:
為什么不在 fetch 呼叫之前嘗試構建資料。
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);
});
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/471052.html
