错误:超过最大更新深度

时间:2018-08-01 17:55:26

标签: javascript reactjs infinite-loop react-select react-props

我的React项目收到此错误:

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.

我不知道是什么导致了无限循环。我正在使用react-select下拉库。也许这与图书馆认为价值在不断变化有关。我不确定。任何帮助都是伟大的,非常感谢。

这是父类代码:

import React, { Component } from "react";
import ReactDOM from "react-dom";
import "./App.css";
import { Grid, Row, Col, PageHeader } from "react-bootstrap";
import AdvDrop from "./AdvDrop";

class App extends Component {
  state = {
    childsName: null
  };

  handleName = newName => {
    this.setState({ childsName: newName });
    console.log("callback called");
  };

  render() {
    return (
      <div className="container-fluid">
        <PageHeader>
          WALI <small>Prototype</small>
        </PageHeader>
        {console.log("parent re-rendered")}
        <AdvDrop
          name={this.state.childsName}
          onNameChanged={this.handleName()}
        />
      </div>
    );
  }
}

export default App;

以及子类代码:

import React, { Component } from "react";
import Select from "react-select";
import "./AdvDrop.css";
import "./App.js";

const options = [
  { value: "chocolate", label: "Chocolate" },
  { value: "strawberry", label: "Strawberry" },
  { value: "vanilla", label: "Vanilla" }
];

class AdvDrop extends Component {
  state = {
    selectedOption: this.props.name
  };

  handleChange = selectedOption => {
    {
      /*this.setState({ selectedOption });*/
    }
    this.props.onNameChanged(selectedOption);
    console.log(`Option selected:`, selectedOption);
  };

  render() {
    const { selectedOption } = this.state;
    return (
      <div>
        {console.log("child re-rendered")}
        <Select
          className="station"
          value={selectedOption}
          onChange={this.handleChange}
          options={options}
        />
      </div>
    );
  }
}

export default AdvDrop;

1 个答案:

答案 0 :(得分:2)

您正在通过编写handleName直接在渲染中调用this.handleName()函数。只需给函数引用提供onNameChanged

class App extends Component {
  state = {
    childsName: null
  };

  handleName = newName => {
    this.setState({ childsName: newName });
    console.log("callback called");
  };

  render() {
    return (
      <div className="container-fluid">
        <PageHeader>
          WALI <small>Prototype</small>
        </PageHeader>
        {console.log("parent re-rendered")}
        <AdvDrop name={this.state.childsName} onNameChanged={this.handleName} />
      </div>
    );
  }
}
相关问题