React中异步锚点的onClick事件

Asynchronous anchor's onClick event in React

我正在尝试跟踪锚标记 (<a>) 在 React 中的点击次数(即在导航发生之前向我的服务器发送 POST 请求)。

我的代码目前是这样的:

<a 
  href="http://example.com"
  onClick={() => axios.post('http://my-server.com', { value: 'Hello' })}
>
  Click Me!
</a>

但问题是因为 POST 请求是异步的, "href event" 发生在请求完成之前,所以请求被取消了。

那么如何在导航发生之前执行异步事件呢?

如果您正在寻找跟踪锚点,您可以使用 ping 属性来实现。检查 this

<a href="/Whosebug" ping="/tracker/going-to-Whosebug">click>

请注意,这并非所有浏览器都支持。

首先在您的点击处理程序中接受一个事件。这将允许您停止导航,直到 post 完成。

Axios returns 发出请求时的承诺。您需要等待它完成,然后再处理您的导航。

(event) => {
   // stop the browser from navigating
   event.preventDefault();
   // save url so that you have the value after the event was disposed
   const redirectUrl = event.target.href;
   axios.post('http://my-server.com', { value: 'Hello' })
   .then(response => {
     // handle success
     console.log(response);
   })
   .catch(error => {
     // handle error
     console.log(error);
   })
   .then(() => {
     // always executed
     // navigate logic here
     console.log(redirectUrl);
   });
}