javascript 错误:超过最大更新深度。当组件重复调用时可能会发生这种情况

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49642401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:41:11  来源:igfitidea点击:

ERROR: Maximum update depth exceeded. This can happen when a component repeatedly calls

javascriptreactjswebreact-redux

提问by firmfiasco

I'm new to react and I've been playing around with it the past few days. Whenever I try to run this simple code below it keeps giving me the error.

我是新来的,过去几天我一直在玩它。每当我尝试在下面运行这个简单的代码时,它总是给我错误。

"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."

“超出了最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 内重复调用 setState 时,可能会发生这种情况。React 限制嵌套更新的数量以防止无限循环。”

I'm not sure why, can anybody please help me? Thank you in advance.

我不知道为什么,有人可以帮助我吗?先感谢您。

import React, { Component } from 'react';
import { render } from 'react-dom';



export default class State1 extends React.Component {

  constructor() {
    this.state = { value: "llll" };
  }

  change() {
    setTimeout(()=>{
      this.setState({value:"eeee"});
    },3000);
  }

  change2() {
      this.setState({value:"eeee"});
  }
  
  render() {
    {this.change2()};
    return (
      <div > {this.state.value} </div >
    ) 
  }


}

回答by themollusk

Every time you invoke setState(), Your component will call the rendermethod to reflect the change in state, which will then invoke change2(), thus causing an endless loop.

每次调用setState(),您的组件都会调用该render方法来反映状态的变化,然后调用change2(),从而导致无限循环。