【问题标题】:What is causing an infinite loop here?是什么导致了这里的无限循环?
【发布时间】:2021-09-19 13:02:21
【问题描述】:

我对 React 比较陌生,我不完全理解我的代码中的哪里调用了重新渲染。我知道该文件非常大,对此感到抱歉:(。我将删除我知道没有任何内容不断重新渲染的区域。

关于地点和原因的任何想法?谢谢。

代码:

function MeetupItem(props) {
    useCallback(() => {
        setAllParticipants(participantContext.getParticipants(props));
        try {
            fetch('http://localhost:3000/users')
                .then(response => {
                    return response.json();
                }).then(data => {
                    const users = [];
                    for (const key in data) {
                        const user = {
                            id: key,
                            ...data[key]
                        };
                        users.push(user);
                    };
                    setAllPossibleParticipants(allParticipants.filter(users));
                    console.log(allParticipants);
                })
        } catch (err) { console.log(err) };
    }, [participantContext, props, allParticipants]);

}

export default MeetupItem;```

【问题讨论】:

  • 尝试从依赖数组中移除allParticipants
  • 没什么,我三个都试过了:(
  • 尝试删除组件中的所有内容并尽可能少地返回(或者甚至只是一开始就返回 null)。确保它只渲染一次。然后逐渐添加东西,直到你看到它导致比你预期的更多的重新渲染。

标签: javascript reactjs web frontend infinite-loop


【解决方案1】:

当你使用useCallback 时,你应该小心地提供依赖数组。您已将 allParticipants 设置为依赖数组,然后您已在代码中修改了此变量的值!因此,每次更改后,您的回调都会再次运行并导致无限循环!

【讨论】:

    【解决方案2】:

    如果此行正在更新allParticipants

    setAllPossibleParticipants(allParticipants.filter(users));
    

    useCallback 将再次被调用,就像你 allParticipants 一样,它是依赖项。

    【讨论】:

      【解决方案3】:

      在您的代码中,您在useCallback 的依赖数组中设置allParticipants,同时在useCallback 内部,您正在更新allParticipants 的状态,这将导致无限循环,因为这个useCallback 将在任何时候执行是依赖数组中的任何项目的变化。

      修改代码:

          useCallback(() => {
              setAllParticipants(participantContext.getParticipants(props));
              try {
                  fetch('http://localhost:3000/users')
                      .then(response => {
                          return response.json();
                      }).then(data => {
                          const users = [];
                          for (const key in data) {
                              const user = {
                                  id: key,
                                  ...data[key]
                              };
                              users.push(user);
                          };
                          setAllPossibleParticipants(allParticipants.filter(users));
                          console.log(allParticipants);
                      })
              } catch (err) { console.log(err) };
          }, [participantContext, props]);
      
      }
      
      export default MeetupItem;
      
      

      看看上面的代码是否解决了你的问题。

      【讨论】:

      • 不得不删除第一行。删除依赖项是不够的:(
      猜你喜欢
      • 2013-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多