使用使用效果钩React的无休止的后端请求

发布于 2025-02-13 21:22:12 字数 410 浏览 0 评论 0原文

我正在尝试向我的后端提出AA请求,因此当我的组件加载时,它可以接收一些数据以渲染。

问题在于,该应用程序以消耗资源的无限请求循环进行。

我在做什么错?

  useEffect(() => {
    Axios.post("http://localhost:3005/people", {UUID}).then((response) => {
        const peopleArray = [];
        for (let key in response.data) {
          peopleArray.push({ ...response.data[key] });
        }
        setPeople(peopleArray);
      });
  });

I'm trying to make a a request to my back-end so when my component loads it can receive some data to render.

the problem is that the application goes in an infinite loop of requests that consumes resources.

what am I doing wrong?

  useEffect(() => {
    Axios.post("http://localhost:3005/people", {UUID}).then((response) => {
        const peopleArray = [];
        for (let key in response.data) {
          peopleArray.push({ ...response.data[key] });
        }
        setPeople(peopleArray);
      });
  });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

忘年祭陌 2025-02-20 21:22:12

您需要一系列依赖性来使用效果,仅在已安装的组件上运行或这些依赖项中的任何一个。就像没有依赖数组一样,它将随着每个渲染而运行,这将导致无限循环。

      useEffect(() => {
    Axios.post("http://localhost:3005/people", {UUID}).then((response) => {
        const peopleArray = [];
        for (let key in response.data) {
          peopleArray.push({ ...response.data[key] });
        }
        setPeople(peopleArray);
      });
  }, []);

You need to an array of dependences to useEffect, to only run on the component mounted or any of these dependencies change. as without an array of dependences, it will run with each render, which will cause an infinite loop.

      useEffect(() => {
    Axios.post("http://localhost:3005/people", {UUID}).then((response) => {
        const peopleArray = [];
        for (let key in response.data) {
          peopleArray.push({ ...response.data[key] });
        }
        setPeople(peopleArray);
      });
  }, []);
沉默的熊 2025-02-20 21:22:12

检查 documentation
或检查此示例 w3school

>

useEffect(() => {
 Axios.post("http://localhost:3005/people", {UUID}).then((response) => {
    const peopleArray = [];
    for (let key in response.data) {
      peopleArray.push({ ...response.data[key] });
    }
    setPeople(peopleArray);
 });
}, []); // <- add empty brackets here

Check the Documentation
or check this example w3school

Only run the effect on the initial render:

useEffect(() => {
 Axios.post("http://localhost:3005/people", {UUID}).then((response) => {
    const peopleArray = [];
    for (let key in response.data) {
      peopleArray.push({ ...response.data[key] });
    }
    setPeople(peopleArray);
 });
}, []); // <- add empty brackets here
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文