不变违规:React Native中超出最大更新深度

我有一个React Native组件,需要在其中使用ComponentDidmount。同样在ComponentDidmount中,我正在使用setState,因为我不确定有其他方法可以解决我的目的。我猜因为这个原因,我得到了错误:Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate。尽管我没有使用componentWillUpdatecomponentDidUpdate。这是我的代码:

   currentUsers=()=>{
        let dbRef = firebase.database().ref('Users');
        dbRef.on('child_added',(val)=>{
            let person = val.val();
            person.phone = val.key;
            this.setState((prevState)=> {
                return {
                    users: [...prevState.users,person]
                }
            })
        })
    }

    componentWillMount(){
      this.currentUsers();
    }

我该怎么办才能解决该错误?

lihaizheng17 回答:不变违规:React Native中超出最大更新深度

so,错误基本上是在render方法中调用func,后者再次调用setState,从而导致无限循环。始终建议在调用render方法时使用匿名函数。因此,替换

onChangeText={this.handleChange('textMessage')} to onChangeText={() =>this.handleChange('textMessage')}

为您服务。希望有帮助。

,

您能为整个Class组件提供代码吗?

本文链接:https://www.f2er.com/3156960.html

大家都在问