componentDidUpdate内部的更新变量失败

时间:2019-10-09 07:36:08

标签: react-native

我的视图中有一个弹出窗口,并且在弹出窗口中有一个倒数计时器。当倒数计时器具有value1时,我需要隐藏弹出窗口。这就是我尝试过的。

componentDidUpdate() {
        if (this.state.count === 1) {
            clearInterval(this.intervalDuration);
            this.setState({popupvisible:false})
        }
    }

当计数等于1时,我得到一个错误。

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

3 个答案:

答案 0 :(得分:0)

您必须在componentDidUpdate中添加条件

componentDidUpdate在DOM更新后需要进行操作时特别有用

componentDidUpdate(prevProps) {
    if (prevProps.data !== this.props.data) {
            if (this.state.count === 1) {
                clearInterval(this.intervalDuration);
                this.setState({popupvisible:false})
            }
        }
    }

您可以在官方文档中了解有关componentDidUpdate的更多信息:

https://reactjs.org/docs/react-component.html#componentdidupdate

答案 1 :(得分:0)

如果要设置状态变量,则也可以在不增加更新的情况下添加该变量。

you just need something like below

import java.util.ArrayList;

public class ReverseArrayList{
  public static void main(String[] args) {
    //  Note: I used a sample array with 6 elements. 
    //  I explain the code as if I am strictly using 6 elements
    //  However this may be done with any # of elements 
    ArrayList<String> reverseMe = new ArrayList<String>();
    reverseMe.add("I");   
    reverseMe.add("am");
    reverseMe.add("going");
    reverseMe.add("to");      
    reverseMe.add("be");
    reverseMe.add("reversed");
    reverseList(reverseMe);
  }
private static void reverseList(ArrayList<String> arrayList){
 //  This loop will run until we reach the midpoint of the array. At the midpoint, all the elements would be reversed
    for (int i = 0; i < reverseMe.size()/2; i++){

      //  Save the first three values for later use. 
      String initial = reverseMe.get(i);

      //  The 1st element will be assigned to the last element, upto the midpoint 
      reverseMe.set(i, reverseMe.get(reverseMe.size() - i - 1));

      //  The last element will be assigned to the 1st element, upto the midpoint
      reverseMe.set(reverseMe.size() - i - 1, initial);
    }
    //  Displays the contents of the arraylist
    for(String i: reverseMe){
      System.out.println(i);
    }

}
}

答案 2 :(得分:0)

之所以发生这种情况,是因为当count达到值1时,您的componentDidUpdate设置了状态,并且由于没有检查来控制何时基于popupVisible更新状态的值,您的componentDidUpdate会被反复调用,从而导致无限循环。您要做的是检查popupVisible是否为true,然后仅将其设置为false。

componentDidUpdate() {
    if (this.state.count === 1) {
        clearInterval(this.intervalDuration);
        if(this.state.popupvisible) {
        this.setState({ popupvisible:false });
        }
    }
}