useEffect 返回未定义,即使“then”返回值响应

我似乎无法弄清楚为什么 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]);  


当年话下
浏览 91回答 1
1回答

一只甜甜圈

提供给 useEffect 的回调必须返回一个函数或未定义(如果提供了一个函数,则这被认为是一个清理函数。清理函数用于分离事件侦听器,取消任何正在进行的请求,并防止如果组件被卸载则进行任何更新)为了访问您的http请求产生的响应,您应该将其存储在一个状态中(您可以使用useState或useReducer)const [rest, setResp] = React.useState();React.useEffect(() => {&nbsp;wait().then(_ => getData()).then(setResp);}, [YOUR_DEPENDENCIES]);// update jsx based on rest根据您问题中的更新,您需要的是轮询请查看下面的示例(请记住,这是说明可能的解决方案的代码)function usePolling(fetcher, interval) {&nbsp; const [payload, setPayload] = React.useState(null);&nbsp;&nbsp;&nbsp; React.useEffect(function () {&nbsp; &nbsp; // you must implement the error handling&nbsp; &nbsp; fetcher()&nbsp; &nbsp; &nbsp; .then(function (resp) {&nbsp; &nbsp; &nbsp; &nbsp; setPayload(resp)&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp;&nbsp;&nbsp; }, [fetcher]);&nbsp;&nbsp;&nbsp; React.useEffect(function () {&nbsp; &nbsp; let timeoutId;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; function poll() {&nbsp; &nbsp; &nbsp; timeoutId = setTimeout(function () {&nbsp; &nbsp; &nbsp; &nbsp; // you must implement the error handling&nbsp; &nbsp; &nbsp; &nbsp; fetcher()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .then(function (resp) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setPayload(resp)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; poll();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; }, interval);&nbsp; &nbsp; }&nbsp; &nbsp; poll()&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return function () {&nbsp; &nbsp; &nbsp; clearTimeout(timeoutId);&nbsp; &nbsp; }&nbsp; }, [fetcher, interval]);&nbsp;&nbsp;&nbsp; return payload;}function App() {&nbsp; const payload = usePolling(function () {&nbsp; &nbsp; return Promise.resolve(Date.now())&nbsp; }, 3000);&nbsp;&nbsp;&nbsp;&nbsp; return (&nbsp; &nbsp; <div>polling payload: {payload}</div>&nbsp; )}ReactDOM.render(<App/>, document.getElementById('app'))<!DOCTYPE html><html><head>&nbsp; <meta charset="utf-8">&nbsp; <meta name="viewport" content="width=device-width">&nbsp; <title>JS Bin</title>&nbsp; <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>&nbsp; <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script></head><body>&nbsp; <div id="app"></div></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript