簡體   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