亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

useEffect 返回未定義,即使“then”返回值響應

useEffect 返回未定義,即使“then”返回值響應

當年話下 2023-11-02 17:04:25
我似乎無法弄清楚為什么 useEffect 會這樣做... Wait() 是一個睡眠異步函數,getData() 是一個 Axios 請求。        return wait().then(getData().then((resp) => {            console.log(resp)        }))此代碼記錄了 resp 變量的有效值,但在 return 語句中返回 undefined。發生了什么事以及如何讓它返回 resp 變量?編輯***const wait = React.useCallback( async() => {    if (loading === false) {        await sleep(4000);    } else if (loading === true){        await sleep(0);    } else {        await sleep(2000);    }}, [loading])const getData = React.useCallback(() => {    const value = Axios.post("http://localhost:3001/api/get-value",    {user: userProp}).then((response) => {        const recievedData = response.data;        const dataValue = recievedData.map((val) => {            return [val.value]        })            if (loading === true){                setLoading(false);            }        return parseInt(dataValue);    }).then((resp) => {        setMoisture(resp) // if I turn this off still no go.        return resp    })    return value}, [userProp, loading])const Data = React.useCallback(() => {    try {        return wait().then(getData)    } catch (error) {        setError(true);        return error;        }   }, [wait, getData])React.useEffect(() => {    let isEffect = false    if (props.location.state !== undefined) {        Data().then((firstResponse) => {            if (!isEffect){                setMoisture(firstResponse)            }        })    }    return () => {        isEffect = true;    }}, [props.location.state, Data, moisture]);  
查看完整描述

1 回答

?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

提供給 useEffect 的回調必須返回一個函數或未定義(如果提供了一個函數,則這被認為是一個清理函數。清理函數用于分離事件偵聽器,取消任何正在進行的請求,并防止如果組件被卸載則進行任何更新)


為了訪問您的http請求產生的響應,您應該將其存儲在一個狀態中(您可以使用useState或useReducer)


const [rest, setResp] = React.useState();


React.useEffect(() => {

 wait().then(_ => getData()).then(setResp);

}, [YOUR_DEPENDENCIES]);


// update jsx based on rest

根據您問題中的更新,您需要的是輪詢


請查看下面的示例(請記住,這是說明可能的解決方案的代碼)


function usePolling(fetcher, interval) {

  const [payload, setPayload] = React.useState(null);

  

  React.useEffect(function () {

    // you must implement the error handling

    fetcher()

      .then(function (resp) {

        setPayload(resp)

      })

    

  }, [fetcher]);

  

  React.useEffect(function () {

    let timeoutId;

    

    function poll() {

      timeoutId = setTimeout(function () {

        // you must implement the error handling

        fetcher()

          .then(function (resp) {

            setPayload(resp)

            poll();

          })

      }, interval);

    }

    poll()

    

    return function () {

      clearTimeout(timeoutId);

    }

  }, [fetcher, interval]);

  

  return payload;

}



function App() {

  const payload = usePolling(function () {

    return Promise.resolve(Date.now())

  }, 3000);

  

 

  return (

    <div>polling payload: {payload}</div>

  )

}


ReactDOM.render(<App/>, document.getElementById('app'))

<!DOCTYPE html>

<html>

<head>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width">

  <title>JS Bin</title>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>

</head>

<body>

  <div id="app"></div>

</body>

</html>


查看完整回答
反對 回復 2023-11-02
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號