ReactJS - 使用 localStorage 作为 useEffect 的依赖项会导致无限循环
此代码在 console.log
行给了我无限循环
const userInfo = JSON.parse(localStorage.getItem("user_info"));
const [filterSemester, setFilterSemester] = useState(SEMESTERS[0]);
const [scoreData, setScoreData] = useState(null);
useEffect(() => {
getData();
}, [userInfo, filterSemester]);
useEffect(() => {
console.log("scoreData: ", scoreData);
}, [scoreData]);
const getData = () => {
const params = {
student_id: userInfo?.student_info?.id,
school_year_id:
userInfo?.student_info?.class_info?.grade_info?.school_year_id,
semester: filterSemester.key,
};
getStudyInfoBySchoolYear(params).then((res) => {
if (res?.status === 200) {
setScoreData(res?.data?.data);
}
});
};
如果我从第一个 useEffect
的依赖项数组中删除 userInfo
,循环就会消失,我想知道为什么?我在代码中根本没有改变它。
This code give me infinite loop at line console.log
const userInfo = JSON.parse(localStorage.getItem("user_info"));
const [filterSemester, setFilterSemester] = useState(SEMESTERS[0]);
const [scoreData, setScoreData] = useState(null);
useEffect(() => {
getData();
}, [userInfo, filterSemester]);
useEffect(() => {
console.log("scoreData: ", scoreData);
}, [scoreData]);
const getData = () => {
const params = {
student_id: userInfo?.student_info?.id,
school_year_id:
userInfo?.student_info?.class_info?.grade_info?.school_year_id,
semester: filterSemester.key,
};
getStudyInfoBySchoolYear(params).then((res) => {
if (res?.status === 200) {
setScoreData(res?.data?.data);
}
});
};
If I remove userInfo
from the dependency array of the first useEffect
, the loop will gone, I wonder why? I didn't change it at all in the code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
userInfo
实际上正在发生变化。它是一个功能组件,因此组件内部的所有代码都将在每次渲染上运行,因此,
userInfo
会在每次渲染上重新创建,因为它没有声明为引用(使用 < code>useRef),或更常见的是,作为状态(使用useState
)。流程如下:
useEffect
运行getData
。第二个useEffect
也会运行。getData
将使用setScoreData
更新scoreData
状态。后者将触发重新渲染,并且scoreData
也已更改,因此第二个useEffect
将运行。userInfo
声明(创建对其的新引用,除非localStorage.getItem("user_info")
返回未定义
)。userInfo
已更改,因此第一个useEffect
将再次运行。您可以将您替换
为
并将您
替换为
userInfo
is actually changing.It is a functional component, so all the code that is inside the component will run on every render, thus,
userInfo
gets re-created on every render, because it was not declared as a reference (withuseRef
) or, more commonly, as a state (withuseState
).The flow is as follows:
useEffect
runsgetData
. The seconduseEffect
also runs.getData
will updatescoreData
state withsetScoreData
. This latter will trigger a re-render, and alsoscoreData
has changed, so the seconduseEffect
will run.userInfo
declaration (creating a new reference to it, unlesslocalStorage.getItem("user_info")
is returningundefined
).userInfo
as changed, so the firstuseEffect
will run again.You could replace your
with
and your
with
试试这个
try this