为什么仅获取数据会导致React组件引起Rerender

发布于 2025-01-21 15:57:57 字数 1298 浏览 5 评论 0原文

我对反应并试图从MySQL获取数据的新手是无限循环的新手。我已经阅读了许多其他帖子,并发现在获取数据时使用使用效果挂钩的最佳实践。我可以看到这样的原因是,在其他帖子中,其他人也使用Usestate来获取数据并更改状态,从而导致无限循环。但是,为什么简单地获取数据而不更改任何状态仍然会导致无限循环?那是因为获取会自动引起组件摄氏剂吗?

const Players = () => {
  const [players, setPlayers] = useState();

  const selectedPlayerName = window.location.search
    ? window.location.search.substring(1).split("=")[1]
    : "DeMar DeRozan";

  getPlayer(selectedPlayerName).then((res) => {
    console.log(res.results[0]);
  });

  

  return (
    <>
      <MenuBar />

      <div style={{ width: "70vw", margin: "0 auto", marginTop: "2vh" }}>
        <img
          // src={process.env.PUBLIC_URL + "/photos/legend.jpg"}
          src="/photos/legend.jpg"
          alt="pc"
        />
        <Table
          dataSource={players}
          columns={playerColumns}
          pagination={{
            pageSizeOptions: [10],
            defaultPageSize: 10,
            showQuickJumper: true,
          }}
        />
      </div>
      <Divider />
    </>

这是我的GetPlayer代码,这只是一个提取。

const getPlayer = async (name) => {
  var res = await fetch(
    `http://${config.server_host}:${config.server_port}/player?name=${name}`
  );
  return res.json();
};

I am fairly new to React and trying to fetch data from mySQL caused an infinite loop. I have read many other posts and found out that the best practice if to use a useEffect Hook when fetch data. I could see the reason being that in other posts others use useState as well to get the data and change the state hence cause the infinite loop. But why does simply fetch data without changing any state would still cause infinite loop? Is that because fetch would automatically cause component rerender?

const Players = () => {
  const [players, setPlayers] = useState();

  const selectedPlayerName = window.location.search
    ? window.location.search.substring(1).split("=")[1]
    : "DeMar DeRozan";

  getPlayer(selectedPlayerName).then((res) => {
    console.log(res.results[0]);
  });

  

  return (
    <>
      <MenuBar />

      <div style={{ width: "70vw", margin: "0 auto", marginTop: "2vh" }}>
        <img
          // src={process.env.PUBLIC_URL + "/photos/legend.jpg"}
          src="/photos/legend.jpg"
          alt="pc"
        />
        <Table
          dataSource={players}
          columns={playerColumns}
          pagination={{
            pageSizeOptions: [10],
            defaultPageSize: 10,
            showQuickJumper: true,
          }}
        />
      </div>
      <Divider />
    </>

this is my code for getPlayer which is simply a fetch.

const getPlayer = async (name) => {
  var res = await fetch(
    `http://${config.server_host}:${config.server_port}/player?name=${name}`
  );
  return res.json();
};

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

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

发布评论

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

评论(3

预谋 2025-01-28 15:57:58

尽管建议在使用效应内部进行副作用操作以避免重新租赁,但在没有使用效果的情况下进行提取会导致重新订阅器,但不应导致无限循环。
尝试运行此代码,

不建议使用此代码,但如果设置状态,则不应引起

export default function App() {
  const result = fetch(
    "https://api.coindesk.com/v1/bpi/currentprice.json"
  ).then((response) => {
    console.log("result", response);
  });
  
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <button onClick={()=>alert('hello')}>hello</button>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

循环

import "./styles.css";
import {useState} from 'react'
export default function App() {
  const [data,setData] = useState([]);

  const result = fetch(
    "https://api.coindesk.com/v1/bpi/currentprice.json"
  ).then((response) => {
    setData([])
    console.log("result", response);
  });
  console.log("result", result);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <button onClick={() => alert("hello")}>hello</button>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

无限
如何在不使用React功能中使用React函数的无用fack数据组件?

although it's recommended to do side effects operations inside a useEffect to avoid re-renders, doing a fetch without a useEffect will cause re-renders but should not cause an infinite loop.
try running this code

this is not recommended but should not cause an infinite loop

export default function App() {
  const result = fetch(
    "https://api.coindesk.com/v1/bpi/currentprice.json"
  ).then((response) => {
    console.log("result", response);
  });
  
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <button onClick={()=>alert('hello')}>hello</button>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

if you set the state then you will have a an infinite loop

import "./styles.css";
import {useState} from 'react'
export default function App() {
  const [data,setData] = useState([]);

  const result = fetch(
    "https://api.coindesk.com/v1/bpi/currentprice.json"
  ).then((response) => {
    setData([])
    console.log("result", response);
  });
  console.log("result", result);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <button onClick={() => alert("hello")}>hello</button>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

also, see this stack overflow thread, it has more insights around this subject
How to fetch data without useEffect hooks in React function component?

匿名。 2025-01-28 15:57:58

我仅使用与获取相关的零件重新创建您的代码,但我没有看到重新渲染,或者至少没有无限循环。

要追踪为什么要恢复某些内容,请在此处查看答案 65425731”> React DevTools Profiler工具。

我还偶然发现了一个名为'您为什么渲染'这将使重新订阅者的原因记录。

I recreated your code using only the parts relevant to the fetch and I'm not seeing a re-render, or at least not an infinite loop.

For tracking down why something rerendered, check the answer here regarding the React Devtools profiler tool.

I also stumbled across a 3rd party library called 'Why Did You Render' that will console log the reason for re-renders.

我们的影子 2025-01-28 15:57:58

我也有一个类似的问题,在提取过程中进行时,组件仍在重新渲染,并在提取完成后停止重新订阅。在我的情况下,问题是该组件被偶然地称为async函数。只需删除async关键字修复了问题即可。我无法解释为什么会发生这种情况,但这也许会对某人有所帮助。

I had a similar issue, the component kept re-rendering while the fetch was in progress and stopped re-rendering when the fetch completed. In my case the issue was that the component was declared accidentally as an async function. Just removing the async keyword fixed the issue. I can't explain why that was happening, but maybe this will help someone.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文