【发布时间】:2020-12-11 08:29:44
【问题描述】:
我似乎无法弄清楚为什么 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]);
【问题讨论】:
-
您的链接不完全正确,您还需要在最后返回值。尝试这样的事情:
return wait().then(getData).then(resp => resp)虽然如果你在最终的.then中除了返回值之外没有做任何事情,那么它实际上不是必需的,你可以省略它 -
谢谢!这解决了我未定义的问题,但我的状态不再更新。
-
好的,但你是如何尝试更新状态的?添加所有相关代码
-
好的,我添加了更多代码。如果您还需要什么,请告诉我。
标签: javascript reactjs asynchronous promise use-effect