反应错误:超过最大更新深度-简单示例

时间:2020-04-04 12:54:09

标签: reactjs function react-props

我试图在master.js组件中使用某些功能。当我运行下面的代码时,我得到了错误 “错误:超过最大更新深度。当组件重复调用componentWillUpdate或componentDidUpdate内部的setState时,可能会发生这种情况。React限制了嵌套更新的数量,以防止无限循环。”

在孙子组件中添加按钮时出现错误

      <button onClick={props.homeHandler()}>change home</button>

如果我注释掉按钮,页面将加载(不包含按钮),因此错误与props.homeHandler()中调用的函数有关

下面是完整的代码

import Child from './child';

class Master extends Component {
  constructor(props) {
    super(props);
    this.state = {
      parentName: 'Parent',
      home: 'Flat'
    };
    this.greetParent = this.greetParent.bind(this);
    this.changeName = this.changeName.bind(this);
    this.changeHome = this.changeHome.bind(this);
  }
  //Event Handlers
  greetParent() {
    console.log(`Hello ${this.state.parentName}`);
  }
  changeName() {
    this.setState({ parentName: 'Paul' });
  }
  changeHome() {
    this.setState({ home: 'semmi detatched' });
  }

  render() {
    return (
      <div>
        <h1>This is master component</h1>
        <h2>My Name is {this.state.parentName}</h2>
        <div>The State From the Master is {this.state.message}</div>
        <Child
          data={this.state}
          greetHandler={this.greetParent}
          nameHandler={this.changeName}
          homeHandler={this.changeHome}
        />
      </div>
    );
  }
}
export default Master;

import React from 'react';
import GrandChild from './grandchild';

export default function Child(props) {
  return (
    <div>
      <h2>the {props.data.parentName}</h2>
      <button onClick={() => props.greetHandler()}>greetme</button>
      <button onClick={() => props.nameHandler()}>Change Name</button>

      <GrandChild
        greetHandler={props.greetHandler}
        nameHandler={props.nameHandler}
        homeHandler={props.homeHandler}
        data={props.data}
      />
    </div>
  );
}

import React from 'react'

export default function GrandChild(props) {
  return (
    <div>
      <h4>I live in a {props.home}</h4>
      <button onClick={props.homeHandler()}>change home</button>
    </div>
  )
}


1 个答案:

答案 0 :(得分:1)

grandChild中,您正在每个渲染上立即调用homeHandler,从而导致状态更新,重新渲染并重复。您需要遵循函数内的模式,而不是自动调用它。

<button onClick={() => props.homeHandler()}>change home</button>