从后端获取数据导致无限循环并且永远无法成功加载

发布于 2025-01-11 14:22:42 字数 1694 浏览 0 评论 0原文

这可能是我对此处显示的异步函数缺乏经验,但我遇到了一个问题,即我从后端获取模板进行反应的代码只是重复,而没有正确设置数据

import React, { useState} from 'react';
import './main.css';
import Frame from './Components/Frame';


function App() {
    const [view, setView] = useState(window.location.pathname);

    console.log('logging view ' + view);

    return (
        <div className="App container m-4">
            <Frame viewF={'nav'} />
            <div id='content'>
                <Frame viewF={view} />
            </div>
        </div>
    );

}

export default App;

主组件的

import React, { useState } from 'react';

function createMarkup(markup) {
    return { __html: markup };
}

const Frame = (props) => {
    const [content, setContent] = useState('');

    const contactBackend = async () => {
        try {
            const response = await fetch('http://localhost:5000/' + props.viewF, {
                'methods': 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            if (!response.ok) {
                throw Error(response.statusText);
            }
            //const data = response.json(); //alternate approach
            //console.log(data);
            setContent(response.json());

        } catch (error) {
            console.log(error);
        }
    }

    contactBackend();

    return (
        <div className="m-2" dangerouslySetInnerHTML={createMarkup(content)}>

        </div>
    )

};

export default Frame;

状态后端可以发送数据,它有效在早期和更简单的版本中。我还可以通过一些控制台日志查看返回值。但它最多放入返回的 div 中的是 [object Promise],然后它会发送 1000 个请求,直到后端崩溃

This is probably my inexperience with Async functions showing here but i'm having an issue where my code to fetch templates from a back-end into react simply repeats without properly setting the state to the data

import React, { useState} from 'react';
import './main.css';
import Frame from './Components/Frame';


function App() {
    const [view, setView] = useState(window.location.pathname);

    console.log('logging view ' + view);

    return (
        <div className="App container m-4">
            <Frame viewF={'nav'} />
            <div id='content'>
                <Frame viewF={view} />
            </div>
        </div>
    );

}

export default App;

main component

import React, { useState } from 'react';

function createMarkup(markup) {
    return { __html: markup };
}

const Frame = (props) => {
    const [content, setContent] = useState('');

    const contactBackend = async () => {
        try {
            const response = await fetch('http://localhost:5000/' + props.viewF, {
                'methods': 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            if (!response.ok) {
                throw Error(response.statusText);
            }
            //const data = response.json(); //alternate approach
            //console.log(data);
            setContent(response.json());

        } catch (error) {
            console.log(error);
        }
    }

    contactBackend();

    return (
        <div className="m-2" dangerouslySetInnerHTML={createMarkup(content)}>

        </div>
    )

};

export default Frame;

The backend can send data, it worked in an earlier and simpler version. I can also see the returned values with some console logs. but the most it ever puts into the returned div is [object Promise] and then it sends 1000s of requests until the back-end crashes

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

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

发布评论

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

评论(1

心意如水 2025-01-18 14:22:42

该代码在函数体中无条件调用 contactBackend,结果是触发组件重新渲染的排队状态更新。这是无意的副作用。

通常,这在安装时在 useEffect 挂钩中调用。

response.json() 还返回一个 Promise,因此您还需要等待它解析。

例子:

useEffect(() => {
  const contactBackend = async () => {
    try {
      const response = await fetch('http://localhost:5000/' + props.viewF, 
        {
          'methods': 'GET',
          headers: {
          'Content-Type': 'application/json'
          }
        }
      );

      if (!response.ok) {
        throw Error(response.statusText);
      }

      const content = await response.json();
      setContent(content);
    } catch (error) {
      console.log(error);
    }
  }

  contactBackend();
}, []); // <-- empty dependency to run once after initial render

The code is unconditionally calling contactBackend in the function body, and the result is an enqueued state update which triggers a component rerender. This is an unintentional side-effect.

Typically this is called in an useEffect hook when mounting.

response.json() also returns a Promise, so you also want to wait for that to resolve.

Example:

useEffect(() => {
  const contactBackend = async () => {
    try {
      const response = await fetch('http://localhost:5000/' + props.viewF, 
        {
          'methods': 'GET',
          headers: {
          'Content-Type': 'application/json'
          }
        }
      );

      if (!response.ok) {
        throw Error(response.statusText);
      }

      const content = await response.json();
      setContent(content);
    } catch (error) {
      console.log(error);
    }
  }

  contactBackend();
}, []); // <-- empty dependency to run once after initial render
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文