useEffect缺少依赖项,但是当我添加依赖项时,出现“超出最大更新深度”错误

时间:2020-01-05 21:01:31

标签: javascript reactjs react-hooks use-effect

我正在尝试使用钩子缠住我的头,并且遇到一个重复的问题。在下面链接的示例中,我有一个useEffect挂钩,用于对数组进行排序。排序顺序由状态值决定,我有一个用于切换状态值的按钮。

一切都按照我预期的方式工作,在安装组件时对数组进行排序,然后单击按钮。

但是,我从linter中得到一个错误,需要在useEffect挂钩中将值的数组声明为依赖项。如果这样做,我会收到“超出最大更新深度”错误。我不确定该怎么办,我将不胜感激!

Link to code

感谢您的光临,对我来说真的很重要!

3 个答案:

答案 0 :(得分:1)

我看不到您的代码有任何问题。我要做的只是通过添加// eslint-disable-next-line react-hooks/exhaustive-deps如下来忽略警告:

useEffect(() => {
    function sortValues() {
      let sorted;
      const array = [...values];
      if (ascValue) {
        sorted = array.sort((a, b) => a - b);
      } else {
        sorted = array.sort((a, b) => b - a);
      }

      setValues(sorted);
    }

    sortValues();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ascValue]);

也许是sortValues()的缩写:

function sortValues() {
    const compare = ascValue ? (a, b) => a - b : (a, b) => b - a;
    setValues([...values].sort(compare));
}

希望对您有帮助!

答案 1 :(得分:1)

理想情况下,您将添加一些条件/检查以查看DependentMethod()是否已具有所需的值。由于 import Foods from "../foods.json"; class Game extends Component { state = { firstFood: Foods[Math.floor(Math.random() * Foods.length)], secondFood: Foods[Math.floor(Math.random() * Foods.length)], mostCalories: "placeholder" }; componentDidMount() { setTimeout( () => { while ( // to check that the two foods' calories are not the same this.state.firstFood.attributes.calories !== this.state.secondFood.attributes.calories ) { console.log(this.state.firstFood.attributes.calories); console.log(this.state.secondFood.attributes.calories); debugger; // an infinite loop because the below setState function doesn't run properly this.setState({ firstFood: Foods[Math.floor(Math.random() * Foods.length)] }); } },2000) } 似乎在每个渲染上都被调用,从而触发了重新渲染,即无穷大。

可能,结合使用Lodash的isEqual和Lodash的orderBy这样的技巧(因为sort会改变原始数组)。

values

重点是,默认情况下,useEffect不应在每个渲染器上都设置状态(渲染完成后,用户可以触发操作)。

A fork of your CodeSandbox to demonstrate,只有在满足条件的情况下,副作用才应更新组件状态。

答案 2 :(得分:1)

这并不令人惊讶-当您在依赖项数组中添加值列表时,useEffect将在值列表的每次更改时执行-导致无限循环:)

根据@norbitrial的先前答案,隐藏错误将无法解决问题,因为必须将范围中的每个依赖项都声明在依赖项数组中,以避免它可能导致意外的行为。

我建议在这种情况下考虑使用useEffect。这将导致可以将依赖项数组的修改逻辑移出useEffect钩子的作用域-并且您不会被迫将其附加为DetachedHouse768的依赖项。