简体   繁体   English

异步 function 在 UseEffect Hook 中不工作

[英]Async function not working inside UseEffect Hook

I am creating an async function inside the useEffect callback.我正在 useEffect 回调中创建一个异步 function。 But because of some reason, every time component renders, I can only see the output from the first console.但由于某种原因,每次组件渲染时,我只能从第一个控制台看到 output。 And execution control never goes inside the async function. Thus returning empty array at the end.并且执行控制永远不会进入异步 function 内部。因此最后返回空数组。

const [targets, setTargets] = useState([]);
useEffect(() => {
    console.log("Inside UseEffect"); //logs the output
    (async () => {
        var url = `https://xx.yy.zz/?param={"request_type":"query_osm_circle","lat":${region.latitude},"lng":${region.longitude},"radius":3,"limit":10}`;
        try {
            let response = await fetch(
                url,
            );
            let responseJson = await response.json();
            console.log(responseJson); //does not log the output
            setTargets(responseJson);
        } catch (error) {
            console.error(error);
        }
    })
});
console.log(targets); //returns empty array
 useEffect(() => {
     console.log("Inside UseEffect"); //logs the output
     (async () => {
         var url = `https://xx.yy.zz/?param={"request_type":"query_osm_circle","lat":${region.latitude},"lng":${region.longitude},"radius":3,"limit":10}`;
         try {
             let response = await fetch(
                 url,
             );
             let responseJson = await response.json();
             console.log(responseJson); //does not log the output
             setTargets(responseJson);
         } catch (error) {
             console.error(error);
         }
     })()
 },[]);

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

相关问题 在 useEffect 钩子的 if 条件内调用异步 function - Calling an async function inside the if condition of useEffect hook 将 useEffect 钩子与“异步”一起使用 - Using useEffect hook with "async" 如何在 React 的 useEffect() Hook 中使用 Async Await - How to use Async Await Inside React's useEffect() Hook 如何简化 React useEffect Hook 中的异步调用 - How to simplify an async call inside a React useEffect Hook 如何在 React useEffect() 挂钩中链接异步方法 - How do I chain async methods inside React useEffect() hook 如何在 React 的 UseEffect() 中调用异步函数? - How to call an async function inside a UseEffect() in React? useEffect 挂钩中的异步/等待不会等待 function - Async/await in useEffect hook doesn't await a function 由于异步 function 在 reactjs 中的 useEffect 钩子中获取数据,因此未定义“对象” - `object' is undefined due to async function that fetched data in useEffect hook in reactjs useEffect 中异步 function 的 React Hook 警告:useEffect function 必须返回清理 function 或什么都不返回 - React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing 在 axios 函数调用中设置状态,然后在 useEffect 钩子中调用函数 - Setting state inside of axios function call, then call function in useEffect hook
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM