[英]React component disappears in a blink when using useEffect()
When I use this the labs
field only gets updated for a millisecond and is gone after that.当我使用它时,
labs
字段只会更新一毫秒,然后就消失了。
// the pagination component
const [state, setState] = useState({
pageCount: 0,
currentPage: 0,
labs: [],
});
useEffect(() => {
labPageCount()
.then((res) => setState({ ...state, pageCount: res.data.pageCount }))
.catch(console.log);
}, [state.pageCount]);
useEffect(() => {
fetchLabs(state.currentPage)
.then((res) => setState({ ...state, labs: res.data }))
.catch(console.log);
}, [state.currentPage]);
Now if I add labs
to the array in the second useEffect()
, then it results in an infinite loop:-现在,如果我在第二个
useEffect()
中将labs
添加到数组中,则会导致无限循环:-
useEffect(() => {
fetchLabs(state.currentPage)
.then((res) => setState({ ...state, labs: res.data }))
.catch(console.log);
}, [state.currentPage, state.labs]);
Inside the second snipped, you are changing the labs by calling setState
, then you are watching the changes on state.labs
which causes the hook to be run again.在第二个片段中,您正在通过调用
setState
更改实验室,然后您正在观察state.labs
上的更改,这会导致挂钩再次运行。
Somehow you need to compare labs then if they are different you should setState
.不知何故,您需要比较实验室,然后如果它们不同,您应该
setState
。
Alternatively you can call fetchLabs where you change the labs instead of calling in useEffect
hook.或者,您可以调用 fetchLabs 更改实验室,而不是调用
useEffect
挂钩。
state
updates in react
are asynchronous
so if you are setting state
multiple times at different places in code. React 中的
state
更新是asynchronous
的,因此如果您在代码中的不同state
react
then directly using the ...state
variable to get the previous value might not work as expected.然后直接使用
...state
变量来获取先前的值可能无法按预期工作。
Instead of setting a state like this -而不是像这样设置 state -
setState({ ...state, pageCount: res.data.pageCount })
Try out this to get the previous value from the state -试试这个从 state 获取以前的值 -
setState((prevState) => ({ ...prevState, pageCount: res.data.pageCount }))
And you need not add state.labs
in dependency array, it will going to cause infinite loop if you are changing value of dependency array inside same useEffect
.而且你不需要在依赖数组中添加
state.labs
,如果你在同一个useEffect
中更改依赖数组的值,它将导致无限循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.