【问题标题】:How to solve Error: Maximum update depth exceeded?如何解决错误:超出最大更新深度?
【发布时间】:2019-08-14 14:59:32
【问题描述】:

我 2 周前开始学习 React Native,并参加了安装插件一章。我安装了 react-native-popover-view,但我不知道,但对我来说,我得到了错误:

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.

我四处搜索,在此停留 2 天后,我了解到我在 render() 中有 setState,因为我在 App render() 中有 Modal。我试图弄清楚如何改变它,但没有成功。

所以我有 Modal.js 类:

class Modal extends Component {
  state = {
    isVisible: true
  }

  closePopover() {
    this.setState({ isVisible: false });
  }

  render() {
    return (
      <View >
        <Popover
          isVisible={this.state.isVisible}
          fromView={this.touchable}
          onRequestClose={() => this.closePopover()}>
          <View style={styles.closeXContainer}>
              <Image source={closeX} style={styles.closeX} onPress={this.closePopover()} />
            </View>
          <Text>I'm the content of this popover!</Text>
        </Popover>
      </View>
    );
  }
}

在 App.js 中,当页面加载时,modal 应该首先启动,覆盖 App.js 组件,可以在背面看到。

class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Modal />
      </View>
    );
  }
}

有人可以帮忙吗?代码应该如何不再出现该错误?

【问题讨论】:

  • onPress={this.closePopover()}更改为onPress={() =&gt; this.closePopover()}
  • 非常感谢尼古拉斯!!!它有效。
  • 为了避免在每次调用时创建一个新函数,你应该这样做:onPress={this.closePopover},不带 (),这样函数就不会在渲染时执行。如果你不传递参数,只传递不带括号的函数。

标签: reactjs react-native


【解决方案1】:

此错误是由于当您在 Image 上调用 onPress={this.closePopover()} 时,它会调用该函数并导致应用程序重新渲染,这再次导致函数被调用,从而导致无限循环。最好的方法是不带括号直接调用它onPress={this.closePopover},或者创建一个匿名函数onPress={() =&gt; this.closePopover()},它只执行一次

【讨论】:

    【解决方案2】:

    你的问题出在函数this.closePopover()的调用上,为了修复它,你只需要把它改成:

    class Modal extends Component {
      state = {
        isVisible: true
      }
    
      closePopover() {
        this.setState({ isVisible: false });
      }
    
      render() {
        return (
          <View >
            <Popover
              isVisible={this.state.isVisible}
              fromView={this.touchable}
              onRequestClose={this.closePopover}>
              <View style={styles.closeXContainer}>
                  <Image source={closeX} style={styles.closeX} onPress={this.closePopover} />
                </View>
              <Text>I'm the content of this popover!</Text>
            </Popover>
          </View>
        );
      }
    }
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-10-13
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 1970-01-01
      • 2021-07-07
      • 2021-06-30
      • 2020-11-26
      相关资源
      最近更新 更多