如何通过点击 React Hooks 方式发送请求?

新手上路,请多包涵

如何使用反应钩子在按钮单击时发送http请求?或者,就此而言,如何对按钮单击产生任何副作用?

到目前为止我看到的是有一些“间接”的东西,比如:

 export default = () => {
  const [sendRequest, setSendRequest] = useState(false);

  useEffect(() => {
    if(sendRequest){
       //send the request
       setSendRequest(false);
    }
  },
  [sendRequest]);

  return (
    <input type="button" disabled={sendRequest} onClick={() => setSendRequest(true)}
  );
}

这是正确的方法还是有其他模式?

原文由 dee zg 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 705
2 个回答
export default () => {
  const [isSending, setIsSending] = useState(false)
  const sendRequest = useCallback(async () => {
    // don't send again while we are sending
    if (isSending) return
    // update state
    setIsSending(true)
    // send the actual request
    await API.sendRequest()
    // once the request is sent, update state again
    setIsSending(false)
  }, [isSending]) // update the callback if the state changes

  return (
    <input type="button" disabled={isSending} onClick={sendRequest} />
  )
}

当您想在单击时发送请求并在发送时禁用按钮时,这就是归结为

更新:

@tkd_aj 指出这可能会发出警告:“无法在未安装的组件上执行 React 状态更新。这是一个无操作,但它表明您的应用程序中存在内存泄漏。要修复,取消所有订阅和异步useEffect 清理函数中的任务。”

实际上,发生的情况是请求仍在处理中,同时您的组件已卸载。然后它会尝试 setIsSending (一个 setState)在一个未安装的组件上。

 export default () => {
  const [isSending, setIsSending] = useState(false)
  const isMounted = useRef(true)

  // set isMounted to false when we unmount the component
  useEffect(() => {
    return () => {
      isMounted.current = false
    }
  }, [])

  const sendRequest = useCallback(async () => {
    // don't send again while we are sending
    if (isSending) return
    // update state
    setIsSending(true)
    // send the actual request
    await API.sendRequest()
    // once the request is sent, update state again
    if (isMounted.current) // only update if we are still mounted
      setIsSending(false)
  }, [isSending]) // update the callback if the state changes

  return (
    <input type="button" disabled={isSending} onClick={sendRequest} />
  )
}

原文由 DoXicK 发布,翻译遵循 CC BY-SA 4.0 许可协议

您不需要在单击按钮时发送请求的效果,而您需要的只是一个处理程序方法,您可以使用 useCallback 方法对其进行优化

const App = (props) => {
   //define you app state here
   const fetchRequest = useCallback(() => {
       // Api request here
   }, [add dependent variables here]);

  return (
    <input type="button" disabled={sendRequest} onClick={fetchRequest}
  );
}

使用带有 useEffect 的变量跟踪请求不是正确的模式,因为您可以将状态设置为使用 useEffect 调用 api,但由于其他一些更改而导致的额外渲染将导致请求进入循环

原文由 Shubham Khatri 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进