ReactJS。无限循环

时间:2018-06-26 10:36:04

标签: reactjs

我正在getCount函数中从孩子那里获得道具。并将其设置为状态。比我尝试在组件中设置它并获得无限循环。我该如何解决?

有上级组件代码:

  import React, { Component } from "react";
import Message from "./Message/Message";

export default class Widget extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      color: {
        s: 30,
        l: 60,
        a: 1
      },
      counter: 0
    };
  }

  getCount = count => this.setState(state => ({
    counter: count
  }));

  getColor = color => {
    console.log(`the color is ${color}`);
  };

  render() {
    const counter = this.state.counter;

    return (
      <div>
        <Message
          getColor={this.getColor}
          getCount={this.getCount}
          color={this.state.color}
        >
          {undefined || `Hello World!`}
        </Message>
        {counter}
      </div>
    );
  }
}

孩子:

import React, { Component } from "react";

export default class Message extends React.Component {
  constructor(props) {
    super(props);
    this.changeColor = this.changeColor.bind(this);

    this.state = { h: 0 };
    this.counter = 0;
  }

  changeColor = () => {
    this.setState(state => ({
      h: Math.random()
    }));
  };

  componentDidUpdate(prevProps) {
    this.props.getColor(this.color);
    this.props.getCount(this.counter);
  }

  render() {
    this.counter++;
    const { children } = this.props;
    const { s, l, a } = this.props.color;

    this.color = `hsla(${this.state.h}, ${s}%, ${l}%, ${a})`;

    return (
      <p
        className="Message"
        onClick={this.changeColor}
        style={{ color: this.color }}
      >
        {children}
      </p>
    );
  }
}

1 个答案:

答案 0 :(得分:2)

问题出在您的Message组件上。

您正在getCount()方法中使用componentDidUpdate()。这将导致您的父级重新渲染,进而使您的Message组件重新渲染。每次重新渲染都会触发另一个重新渲染,并且循环永远不会停止。

您可能希望添加一个检查,以仅在道具已更改时运行该功能。像这样:

componentDidUpdate(prevProps) {
  if(prevProps.color !== this.props.color) {
    this.props.getColor(this.color);
    this.props.getCount(this.counter);
  }
}

这将保留您所需的功能,但不仅会阻止无限循环,而且还会阻止不必要的更新。