【问题标题】:React useEffect calls API too many time, How can I limit the API call to only once when my component renders?React useEffect 调用 API 的时间太多,当我的组件渲染时,如何将 API 调用限制为一次?
【发布时间】:2021-07-12 06:57:02
【问题描述】:

我在 useEffect 挂钩中调用 get API,以在组件挂载之前获取数据, 但它多次调用 API,我收到错误“To many API calls”。

const [total, setTotal] = useState(0);
const [message, setMessage] = useState('');

useEffect(() => {
    covidApi.getData({url:'/totals'})
    .then((response) => {
        setTotal(response.data[0]);
        setMessage('');
        console.log(response.data);
    })
    .catch((error) => {
        setMessage("No data found");
        console.log(error);
    })
});

输出:

请告诉我,在使用 useEffect 钩子渲染组件之前,这是从 API 获取数据的最佳方式。

【问题讨论】:

  • empty array 作为效果的依赖:useEffect(() => { ... }, [])。现在这个效果只会在组件挂载时运行一次。
  • 依赖数组未定义,[] :(如果依赖变化太频繁,你可能想看看debouncingthrottling机制
  • 非常感谢@AjeetShah,它成功了。如果你有的话,你能分享一些关于它的文章(如何使用 useEffect 作为不同的生命周期方法)
  • 看这篇解释useEffect所有用例的文章dmitripavlutin.com/react-useeffect-explanation

标签: reactjs react-hooks use-effect


【解决方案1】:

useEffect 中的函数后面加上[],如下所示:

useEffect(() => {
    covidApi.getData({url:'/totals'})
    .then((response) => {
        setTotal(response.data[0]);
        setMessage('');
        console.log(response.data);
    })
    .catch((error) => {
        setMessage("No data found");
        console.log(error);
    })
}, []);

这只会调用 API 一次。

【讨论】:

    猜你喜欢
    • 2020-05-09
    • 2022-01-16
    • 2017-04-17
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多