英文:
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(() => {
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()
}, [])
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(() => {
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;
}, []);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论