如何在 React 的 UseEffect() 中调用异步函数? [英] How to call an async function inside a UseEffect() in React?

查看:78
本文介绍了如何在 React 的 UseEffect() 中调用异步函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用一个异步函数并获取我的 UseEffect 的结果.

我在网上找到的fetch api例子是直接在useEffect函数中制作的.如果我的 URL 发生变化,我必须修补我所有的提取.

当我尝试时,我收到一条错误消息.

这是我的代码.

<代码>异步函数 getData(userId) {const data = await axios.get(`http://url/api/data/${userId}`).then(承诺=> {返回promise.data;}).catch(e => {控制台错误(e);})返回数据;}功能blabla(){const [data, setData] = useState(null);useEffect(async() => {设置数据(获取数据(1))}, []);返回 (<div>这是{数据[名称"]}

);}

index.js:1375 警告:除了用于清理的函数之外,效果函数不得返回任何内容.看起来你写了 useEffect(async () => ...) 或者返回了一个 Promise.相反,在您的效果中编写异步函数并立即调用它:

useEffect(() => {异步函数 fetchData() {//你可以在这里等待const response = await MyAPI.getData(someId);//...}取数据();}, [someId]);//或者 [] 如果效果不需要道具或状态

解决方案

在你的 effect 中创建一个异步函数,等待 getData(1) 结果然后调用 setData():

useEffect(() => {const fetchData = async() =>{const 数据 = 等待 getData(1);设置数据(数据);}取数据();}, []);

I would like to call an async function and get the result for my UseEffect.

The fetch api examples i found on the internet are directly made in the useEffect function. If my URL changes, i must patch all my fetchs.

When i tried, i got an error message.

This is my code.


    async function getData(userId) {
        const data = await axios.get(`http://url/api/data/${userId}`)
            .then(promise => {
                return promise.data;
            })
            .catch(e => {
                console.error(e);
            })
            return data;
    }


    function blabla() {
        const [data, setData] = useState(null);

        useEffect(async () => {
            setData(getData(1))
        }, []);

        return (
            <div>
                this is the {data["name"]}
            </div>
        );
    }

index.js:1375 Warning: An effect function must not return anything besides a function, which is used for clean-up. It looks like you wrote useEffect(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:

useEffect(() => {
  async function fetchData() {
    // You can await here
    const response = await MyAPI.getData(someId);
    // ...
  }
  fetchData();
}, [someId]); // Or [] if effect doesn't need props or state

解决方案

Create an async function inside your effect that wait the getData(1) result then call setData():

useEffect(() => {
  const fetchData = async () => {
     const data = await getData(1);
     setData(data);
  }

  fetchData();
}, []);

这篇关于如何在 React 的 UseEffect() 中调用异步函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆