英文:
UseEffect endless loop
问题
I'm new to React and I'm trying to learn why I have an endless loop with the following code. I'm using firebase to retrieve a single document.
import services from '../utilities/services';
import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
function SchoolDetail() {
const { schoolID } = useParams();
const [school, setSchool] = useState();
const [id, setID] = useState(schoolID);
useEffect(() => {
services.getSchool(schoolID).then((response) => {
setSchool(response);
}).catch((e) => {
alert("Error occurred while fetching the school. " + e);
}, [id])
})
return (
<>
{(school) && console.log(school.id)}
Details
</>
);
}
export default SchoolDetail;
I've tried using [] as the useEffect dependency and still get an endless loop. I've tried [schoolID], and I've tried the state variable [id]. All cause an endless loop. What am I missing? Is it something to do with the getSchool
function returning a promise?
英文:
I'm new to React and I'm trying to learn why I have an endless loop with the following code. I'm using firebase to retrieve a single document.
import services from '../utilities/services';
import {useState, useEffect} from 'react';
import {useParams} from 'react-router-dom';
function SchoolDetail(){
const {schoolID} = useParams();
const [school, setSchool] = useState();
const [id, setID] = useState(schoolID);
useEffect(()=>{
services.getSchool(schoolID).then((response) => {
setSchool(response);
}).catch((e) => {
alert("Error occured while fetching the school. " + e);
},[id])
})
return(
<>
{(school) && console.log(school.id)}
Details
</>
);
}
export default SchoolDetail;.
I've tried using [] as the useEffect dependency and still get an endless loop. I've tried [schoolID], and I've tried the state variable [id]. All cause an endless loop. What am I missing? Is is something to do with the getSchool function returning a promise?
答案1
得分: 1
问题是由于没有将依赖数组作为useEffect
的第二个参数传递,并且在useEffect
回调内部设置了id
状态,这会触发useEffect
的重复调用。
为了确保useEffect
仅在挂载时运行一次,您应该将一个空数组作为依赖数组传递:
useEffect(() => {
...
}, []);
此外,您可以删除id
状态并直接使用schoolID
作为useEffect
的依赖项:
const { schoolID } = useParams();
const [school, setSchool] = useState();
useEffect(() => {
...
}, [schoolID]);
英文:
The problem of an endless loop is caused by not passing a dependency array as the second argument of useEffect
, and by setting the id
state inside the useEffect
callback, which triggers the useEffect
to be called repeatedly.
To ensure that useEffect
only runs once, on mount, you should pass an empty array as the dependency array:
useEffect(() => {
...
}, []);
Moreover you can remove the id
state and directly use schoolID
as the dependency of useEffect:
const { schoolID } = useParams();
const [school, setSchool] = useState();
useEffect(() => {
...
}, [schoolId]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论