React 18 useEffect 钩子会获取数据两次

huangapple go评论70阅读模式
英文:

React 18 useEffect hook pulling data twice

问题

我是新手学习React,如果这个问题已经有人提过了,真的很抱歉。

我正在使用useEffect钩子从API获取数据,我只想获取一次,但不知何故它被获取了两次。

以下是useEffect钩子的代码:

useEffect(() => {
    const fetchTasks = async () => {
      const res = await fetch('http://localhost:8080/tasks')
      const data = await res.json()
      console.log(data)
      for (let i = 0; i < data.length; i++) {
        setNewTaskContent(newTaskContent => [...newTaskContent, <Task task={data[i]} />])
      }
    }
    fetchTasks()
  }, [])

这本应该在页面加载时运行一次,但我却得到了两次数据数组。

如果我从钩子中删除依赖数组,它会不断地在循环中获取数据。

英文:

I am new to react so really sorry if this question has already been asked.

I am fetching data from an API in an useEffect hook and I only want to fetch it once but instead its being fetched twice for some reason.

Here's the code of useEffect hook

useEffect(() =&gt; {
    const fetchTasks = async () =&gt; {
      const res = await fetch(&#39;http://localhost:8080/tasks&#39;)
      const data = await res.json()
      console.log(data)
      for (let i = 0; i &lt; data.length; i++) {
        setNewTaskContent(newTaskContent =&gt; [...newTaskContent, &lt;Task task={data[i]} /&gt;])
      }
    }
    fetchTasks()
  }, [])

This was supposed to run once when the page was loaded but I am getting an array of data twice.

And if I am removing the dependency array from the hook, its fetching data continuously in a loop.

答案1

得分: 2

严格模式下,React 在开发过程中会渲染每个组件两次。为了防止获取重复数据,你应该从useEffect中返回一个清理函数,它会忽略当前的请求。(除非你有非常充分的理由,不要禁用严格模式。)

useEffect(() => {
	let ignore = false;
    const fetchTasks = async () => {
      const res = await fetch('http://localhost:8080/tasks')
      const data = await res.json();
      if (ignore) return;
      for (let i = 0; i < data.length; i++) {
        setNewTaskContent(newTaskContent => [...newTaskContent, <Task task={data[i]}/>])
      }
    }
    fetchTasks();
	return () => ignore = true;
}, []);
英文:

In strict mode, React will render every component twice during development. To prevent getting duplicate data, you should return a cleanup function from useEffect that ignores the current request. (Do not disable strict mode unless you have a very good reason to.)

useEffect(() =&gt; {
	let ignore = false;
    const fetchTasks = async () =&gt; {
      const res = await fetch(&#39;http://localhost:8080/tasks&#39;)
      const data = await res.json();
      if (ignore) return;
      for (let i = 0; i &lt; data.length; i++) {
        setNewTaskContent(newTaskContent =&gt; [...newTaskContent, &lt;Task task={data[i]}/&gt;])
      }
    }
    fetchTasks();
	return () =&gt; ignore = true;
}, []);

huangapple
  • 本文由 发表于 2023年3月31日 04:02:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75892530.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定