繁体   English   中英

循环请求与 axios 反应

[英]Loop requests in react with axios

我在后端定义了一个套接字,它接受对服务器的连续请求。 现在,我想连续向后端 API 发送请求,直到按下停止按钮。 所以,我可以使用一个循环(坏习惯)。 问题是它从不检查更新的 state。那么,我怎样才能用最好的编码实践来实现它呢?

  1. 我在 Next.JS 中为客户端和服务器使用了两个不同的页面。 服务器有一个简单的按钮来启动和停止服务器,当按钮设置为启动时,它应该不断接受请求并更新响应 state,当按钮设置为停止时,它应该停止请求。
const [close, closeButton] = useBoolean() // State for close button
let req;
proto ? req = 'UDP' : req = 'TCP' // There is a checkbox to select the connection mode. proto is a state.
console.log(`Close button: ${close}`) // This state updates correctly. 

const onSubmit = async () => {
   while(!close)
        console.log(`Close button: ${close}`) // This state does not update while staying in the loop.
        const res = await serverRequest(req) 
        console.log(res.messageFromClient)
    }
}

那么,我应该如何让它无限期运行直到按下关闭按钮。 我应该将 redux 用于全局 state 还是有比 while 循环更好的方法?

客户端代码供参考:

 const onSubmit = async values => {
        const clientData = await clientRequest({proto, JSON.stringify(values.message)})
        console.log(clientData)
        console.log(values.message)
    }

每次从客户端发送消息时,此代码都会发送客户端数据。 所以,为了运行客户端,服务器应该不断地监听请求。 每当客户端发送请求时,服务器应该得到响应并再次启动服务器,直到更改连接模式或在服务器端代码中按下关闭按钮。

如果您绝对必须使用此代码,并希望它访问更新的 state,那么您可以在 React ref 中缓存 state 的副本并改为引用它。

const [close, closeButton] = useBoolean() // State for close button
const closeRef = React.useRef();

React.useEffect(() => {
  closeRef.current = close; // <-- cache close value when it updates
}, [close]);

const onSubmit = async () => {
  while(!closeRef.current) // <-- cached close state value
    console.log(`Close button: ${closeRef.current}`)
    const res = await serverRequest(req) 
    console.log(res.messageFromClient)
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM