如何根据使用 ReactJS 和 Axios 单击的按钮将用户 onClick 事件发送到不同的端点 url

how to send a user onClick event to different endpoint urls based on the button clicked using ReactJS and Axios

我将 react hooksaxiosreact-boostrap 一起使用,并且我在同一页面上有两个按钮,它们是同一表单的一部分,因为它们应该发送字段...

我想要实现的是根据在前端单击的按钮将用户发送到不同的端点url。

目前 onSubmit/onClick 事件没有做任何事情,这意味着事件根本没有被触发,我尝试了下面的代码并将 buttonURLState 作为参数添加到 handleSubmit 函数(它首先在类型上失败,然后我通过 buttonURLState: void)但仍然没有触发任何东西。

form.tsx

const [buttonState, setButtonState] = useState("");

...

let buttonURLState: any = null;

  if (buttonState === "sendToURL1") {
    buttonURLState = "someURL1"; 
  }

  if (buttonState === "sendToURL2") {
    buttonURLState = "someURL2"; 
  }

 const handleSubmit = (e: React.FormEvent) => {
      e.preventDefault();

      axios.post(`http: //www.foo.com/${buttonURLState}/`, data, options)
      .then(response => {
        ...
  }

return
  ....
   <Form onSubmit={handleSubmit}>
      <Form.Label>Name</Form.Label>
         <Form.Group role="form" controlId="name">
           <Form.Control
             autoFocus
             required
             size="lg"
             className="submit-button-text"
             type="text"
             name="name"
             value={fields.name}
             onChange={handleFieldChange}
          />
          ...
          <div>
            <div>
             <Button size="lg" variant="secondary" onClick={() => setButtonState("sendToURL1")}>Send Me to URL1</Button>
            </div>
            <div>
             <Button size="lg" variant="primary" onClick={() => setButtonState("sendToURL2")}>Send Me to URL2</Button>
            </div>
           </div> 
          </Form>

...

PS:不要介意上面端点URL中的space,这是一种能够post向本网站提问的方法

有没有我做错了什么,如果能帮助发送到不同的 urls 端点,我们将不胜感激

您可能根本不需要此处的表单标签。只需从每个按钮调用一个完全独立的函数:

const goToUrl1 = async () => {
  const res = await axios.post('foo.com/url1/', { name: fields.name })
  console.log(res.data)
}

const goToUrl2 = async () => {
  const res = await axios.post('foo.com/url2/', { name: fields.name })
  console.log(res.data)
}

<div>
  <Button onClick={() => goToUrl1()}>Send Me to URL1</Button>
</div>
<div>
  <Button onClick={() => goToUrl2()}>Send Me to URL2</Button>
</div>