React Hook useEffect:使用 axios 和 async await .api 调用连续相同的 api 获取数据 [英] React Hook useEffect : fetch data using axios with async await .api calling continuous the same api

查看:46
本文介绍了React Hook useEffect:使用 axios 和 async await .api 调用连续相同的 api 获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我从 API 获取数据并使用 useEffect 将响应设置为数组它调用API重复连续.

While I fetch data from API and set the response to a array using useEffect it call the API repeat continuous.

let [product, setproduct] = useState([]);

async function fetchData() {
    let response = await axios(
      `api`
    );
    let user = await response.data;
    setproduct(user);
    console.log(product);
  }

  useEffect(() => {
    fetchData();
  }); 

推荐答案

来自 docs,

useEffect 是否在每次渲染后运行?是的!默认情况下,它会在第一次渲染之后和每次更新之后运行.(我们稍后将讨论如何自定义它.)与其考虑安装"和更新",您可能会发现更容易认为效果发生在渲染之后".React 保证 DOM 在它运行效果时已经更新.

Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update. (We will later talk about how to customize this.) Instead of thinking in terms of "mounting" and "updating", you might find it easier to think that effects happen "after render". React guarantees the DOM has been updated by the time it runs the effects.

你可以提供空的依赖数组/[]作为useEffect的第二个参数,它和componentDidMount一样,只会执行一次在组件生命周期中.

You can provide the empty dependency array / [] as second argument to useEffect, it is same as componentDidMount which will executes only once in component life cycle.

useEffect(() => {
    fetchData();
}, []); //This will run only once 

这篇关于React Hook useEffect:使用 axios 和 async await .api 调用连续相同的 api 获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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