反应使用效应不断提取

发布于 2025-02-12 01:19:07 字数 1313 浏览 0 评论 0原文

我正在使用usefect从数据库获取数据,然后代码显示该列表的数据。

  useEffect(() => {
    console.log("triggered")
    fetch("http://localhost:8080/group/getAll")
    .then(response => response.json())
    .then(data => {
      setGroups(data)
    })
  })

我注意到触发在几秒钟内被打印到数千次,因此我假设它不断向DB发送请求。

这是预期的行为吗?如果没有,我该如何修复?

PS我知道[]参数仅渲染一次。但是,是否有一种方法可以使使用效应正确起作用(仅在网页上 groups 重读者时获取数据)

-----编辑------

这就是我使用组

  const createGroup = groups.map((group, i) => {
    return (
      <Dropdown.Item 
        key = {i}
        onClick = {showUser}
        id = {group["groupId"]}
      >
      {group["groupName"]}
      </Dropdown.Item> 
    )
  })

create> create> create> create> create>

<Dropdown.Menu>
  {createGroup}
</Dropdown.Menu>

----编辑2 ---------- 我了解依赖性阵列的工作方式。我尝试了[groups],但这没有改变任何东西。我还尝试了[createGroup],但是出现了一个错误,因为该功能首先未初始化。我可以在依赖项数组中添加HTML元素或其他内容吗?使用我的代码结构,我应该在那里放置什么?

I'm using useEffect to fetch data from DB and later the code displays that list of data.

  useEffect(() => {
    console.log("triggered")
    fetch("http://localhost:8080/group/getAll")
    .then(response => response.json())
    .then(data => {
      setGroups(data)
    })
  })

I noticed that triggered got printed to console thousands of times in a couple seconds so I'm assuming it's constantly sending request to the DB.

enter image description here

Is this the expected behavior? And if not, how to I fix it?

p.s. I know with the [] parameter it only renders once. But is there a way to make useEffect work correctly (only fetch data when groups rerenders on the webpage)

-----edit-----

This is how I used groups

  const createGroup = groups.map((group, i) => {
    return (
      <Dropdown.Item 
        key = {i}
        onClick = {showUser}
        id = {group["groupId"]}
      >
      {group["groupName"]}
      </Dropdown.Item> 
    )
  })

And createGroup

<Dropdown.Menu>
  {createGroup}
</Dropdown.Menu>

----edit2-------
I understand how dependency arrays work. I tried [groups] but that didn't change anything. I also tried [createGroup] but got an error because the function was not initialized at first. Can I add an HTML element or something to the dependency array? With the structure of my code what exactly should I put in there?

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

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

发布评论

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

评论(3

柒夜笙歌凉 2025-02-19 01:19:07

您应该指定状态变量或道具,当更改时应触发使用效率,如以下:

useEffect(() => {
    console.log("triggered")
    fetch("http://localhost:8080/group/getAll")
    .then(response => response.json())
    .then(data => {
      setGroups(data)
    })
  }, [x , y]);

x and y可以是状态变量,Prop,或两者兼有。只有当这些值会改变时,使用效率才会触发。

You should specify, the state variables or the props, which when changed should trigger the useEffect, like this:

useEffect(() => {
    console.log("triggered")
    fetch("http://localhost:8080/group/getAll")
    .then(response => response.json())
    .then(data => {
      setGroups(data)
    })
  }, [x , y]);

Here x and y, can be state variables, props, or both. Only when the values of these will change, then the useEffect will trigger.

兔姬 2025-02-19 01:19:07

关于:

我注意到触发的触发器在几秒钟内被打印到数千次,所以我假设它不断将请求发送到DB。

这已经得到了回答,对于您的用例,这不是预期的行为,因为您似乎想从数据库获取数据,

fetch("http://localhost:8080/group/getAll")

收集JSON

.then(response => response.json())

并使用setGroups

.then(data => {
  setGroups(data)
})

也就是说:

do 您想要使用 to 工作正确

根据其代码中的用法,它似乎可以按设计工作。如果要使用useffect触发重新渲染,则要除了groups以外的其他状态变量,正如许多评论员和用户所指出的那样,引起无限循环。

问问自己:您是否希望再次拨打API电话? (因此,重新渲染)基于group的选择,从&lt; dropdown&gt;

然后,在&lt; dropdown&gt;中选择的值需要传递给useffect的依赖项数组

Regarding:

I noticed that triggered got printed to console thousands of times in a couple seconds so I'm assuming it's constantly sending request to the DB.

This has already been answered, and no, for your use case, this isn't the expected behavior since you seem to want to fetch data from the DB,

fetch("http://localhost:8080/group/getAll")

collect the JSON,

.then(response => response.json())

and set a state variable using setGroups

.then(data => {
  setGroups(data)
})

That said, regarding:

But is there a way to make useEffect work correctly (only fetch data when groups rerenders on the webpage)

How do you want the useEffect to work correctly ?

Per its usage in your code, it seems to working as designed. If you want to trigger a re-render using useEffect you are going to want another state variable other than groups, which, as many commentators and users pointed out, is going to cause an infinite loop.

Ask yourself: Do you want the API call to be made again? (and hence the re-render) based on the selection of a group from <Dropdown>?

Then the value that was selected in the <Dropdown> needs to be passed to the dependency array of useEffect

落在眉间の轻吻 2025-02-19 01:19:07

我相信您应该首先了解组件生命周期概念(可能带有类组件),然后了解如何使用钩子和功能组件复制生命周期。

我在这里提供了一个解释,希望这种解释可能会有所帮助。

请比较这三个片段:

摘要#1:

// This snippet (#1) runs on every render because there is no dependencies.
// So if the component gets updated then it will be re-rendered.
// Consequently, this effect will be fired again (and again if the effect updates the component state).
useEffect(() => {
    // fetch logic [...]
    console.log("runs every time component is re-rendered");
});

摘要#2:

// This snippet (#2) runs on mount. It's similar to componentDidMount on class components.
// Notice there is an empty array of dependencies as a second argument.
// You can fetch data when page is loaded with this snippet.
useEffect(() => {
    // fetch logic [...]
    console.log("runs only when component was mounted");
}, []);

摘要#3:

// This snippet (#3) runs when values on dependency array change, like url variable.
// You can select your array of dependencies. Be aware when some dependency gets updated.
useEffect(() => {
    console.log("triggered only when dependencies change")
    fetch(url)
    .then(response => response.json())
    .then(data => {
        setGroups(data)
    })
}, [url]);

祝您有美好的一天!

I believe you should understand component lifecycle concepts first (probably with class components), then understand how lifecycle can be replicated with hooks and functional components.

I put here an explanation, I hope this explanation could be helpful.

Please, compare these three snippets:

Snippet #1:

// This snippet (#1) runs on every render because there is no dependencies.
// So if the component gets updated then it will be re-rendered.
// Consequently, this effect will be fired again (and again if the effect updates the component state).
useEffect(() => {
    // fetch logic [...]
    console.log("runs every time component is re-rendered");
});

Snippet #2:

// This snippet (#2) runs on mount. It's similar to componentDidMount on class components.
// Notice there is an empty array of dependencies as a second argument.
// You can fetch data when page is loaded with this snippet.
useEffect(() => {
    // fetch logic [...]
    console.log("runs only when component was mounted");
}, []);

Snippet #3:

// This snippet (#3) runs when values on dependency array change, like url variable.
// You can select your array of dependencies. Be aware when some dependency gets updated.
useEffect(() => {
    console.log("triggered only when dependencies change")
    fetch(url)
    .then(response => response.json())
    .then(data => {
        setGroups(data)
    })
}, [url]);

Have a great day!

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