简体   繁体   English

如何修复 React useEffect() 的无限循环?

[英]How to fix Infinite Loop of React useEffect()?

Why is my page rendered so many times?为什么我的页面被渲染了这么多次? How do I fix this?我该如何解决? I need to monitor my dependencies我需要监控我的依赖项

 const [movie, setMovie] = useState(value);

 useEffect(() => { 
    if (canLoad) { 
      const filteredMovie = value.filter( val => val.id !== id);
      setMovie(filteredMovie);
      console.log("movie after filtering", movie); // NOT FILTERED 
    } 
  }, [canLoad, movie]);

after this code i got infinitive loop... when i remove selected from dependencies this is work okay but i need to check and monitoring selected because i need to change state.在这段代码之后,我得到了不定式循环......当我从依赖项中删除选择时,这没关系,但我需要检查和监控选择,因为我需要更改 state。

react not updating immediately my state because i need to set to depedencies.反应不立即更新我的 state 因为我需要设置为依赖。

How to fix this?如何解决这个问题?

movie changes inside this useEffect where has movie as dependency. movie在这个 useEffect 中发生变化,其中movie作为依赖项。 when changing movie inside useEffect, it gonna trigger again because movie its one of its dependencies当在 useEffect 中更改电影时,它会再次触发,因为电影是它的依赖项之一

useEffect(() => { 
    if (canLoad) { 
      const filteredMovie = value.filter( val => val.id !== id);
      setMovie(filteredMovie);
      console.log("movie after filtering", movie); // NOT FILTERED 
    } 
  }, [canLoad]); // remove movie from here

useEffect(() => {do something if canLoad changes}, [canLoad]} useEffect(() => {如果 canLoad 改变就做点什么}, [canLoad]}

useEffect(() => {do something if movie changes}, [movie]) useEffect(() => {如果电影改变了做点什么}, [电影])

you can chain multiple useEffects.您可以链接多个 useEffects。

Let's break down what's happening.让我们分解正在发生的事情。 Javascript runs in an event loop, so calls to hooks like setMovie are not synchronous, their updates will become available in the next iteration of the loop. Javascript 在事件循环中运行,因此对 setMovie 等钩子的调用不是同步的,它们的更新将在循环的下一次迭代中可用。 This means that when you call setMovie(filteredMovie) , movie does not immediately change - it will become available in the next iteration of the event loop, but that won't happen until the effect finishes executing.这意味着当您调用setMovie(filteredMovie)时, movie不会立即更改 - 它会在事件循环的下一次迭代中可用,但直到效果完成执行后才会发生。 That's why printing movie in the console stays the same at this point.这就是为什么此时在控制台中打印movie保持不变的原因。 However, movie does change.然而, movie确实发生了变化。 So adding it to the dependency array at the end means that every time movie is changed, the effect will re-execute.所以最后添加到依赖数组中意味着每次movie改变时,效果都会重新执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM