【问题标题】:Invariant Violation: Maximum update depth exceeded in React Native不变违规:React Native 中超过了最大更新深度
【发布时间】:2019-11-05 19:22:27
【问题描述】:

我有一个 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();
    }

我可以做些什么来解决这个错误?

【问题讨论】:

  • 这看起来不错。你能分享完整的组件 sn-p 吗?
  • 这是组件:codeshare.io/5wWDdK。当我尝试导航到该组件时抛出错误:codeshare.io/G8jzyB@Easwar
  • 这两个文件的内容相同。
  • 很抱歉。这是主屏幕:codeshare.io/2W9pdd。错误显示按下导航到聊天屏幕。
  • 在聊天界面你能不能把 onChangeText={this.handleChange('textMessage')} 换成 onChangeText={() =>this.handleChange('textMessage')}

标签: javascript reactjs react-native


【解决方案1】:

so ,错误基本上是在 render 方法中调用了一个 func 再次调用 setState ,因此是一个无限循环。在调用 render 方法时始终建议使用匿名函数。所以替换

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

为您工作。希望对您有所帮助。

【讨论】:

    【解决方案2】:

    您能否提供整个 Class 组件的代码?

    【讨论】:

    猜你喜欢
    • 2019-12-03
    • 2020-08-11
    • 2019-08-29
    • 1970-01-01
    • 2019-12-03
    • 2022-01-16
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多