簡體   English   中英

ReactJs 中的后置條件數據

[英]Post Conditional Data in ReactJs

所以我想在 React 的 POST 方法 function 中添加條件語句。 我有一個名為 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>
  );
}

我非常感謝任何幫助。 謝謝

為什么不嘗試在獲取調用之前構建數據。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM