Reactjs。渲染柜台

时间:2018-06-26 08:39:35

标签: reactjs

如何对呈现父级中的子组件进行计数?

我有2个组成部分Widget(父级)和Message(子级)。我将计数器从子级传递到父级,并尝试将获取值从子级设置为状态。我犯错了:Maximum update depth exceeded.

组件Message

    import React, { Component } from "react";

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

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

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

  changeCount = () => {
    this.setState(state => ({
      counter: ++state.counter
    }));
  };

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

  render() {
    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>
    );
  }
}

父级组件:

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: state.counter
  }));

  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>
    );
  }
}

我做错了什么?

4 个答案:

答案 0 :(得分:1)

export default class Message extends React.Component {
    constructor() {
        this.counter = 0;
    }

    render() {
        this.counter++;
        ........
    }
}

答案 1 :(得分:1)

@Yossi 的回答计算了所有组件实例的总渲染次数。此解决方案计算单个组件已完成的渲染和重新渲染次数。

用于计算组件实例渲染

import { useRef } from "react";


export const Counter = props => {
    const renderCounter  = useRef(0);
    renderCounter.current = renderCounter.current + 1;
    return <h1>Renders: {renderCounter.current}, {props.message}</h1>;
};

答案 2 :(得分:0)

componentDidUpdate正在调用this.changeCount(),组件更新后,{strong}每次都会调用this.setState(),这当然会无限运行并引发错误。

 componentDidUpdate(prevProps) {
    this.props.getColor(this.color);
    // Add a if-clause here if you really want to call `this.changeCount()` here
    // For example: (I used Lodash here to compare, you might need to import it)
    if (!_.isEqual(prevProps.color, this.props.color) {
        this.changeCount();
    }
    this.props.getCount(this.state.counter);
  }

答案 3 :(得分:0)

为了计算渲染数量,我向所有组件添加了一个静态变量,并在render()中对其进行了递增。

对于Class组件:

import React, { Component } from 'react';
import { View, Text } from 'react-native';
let renderCount = 0;

export class SampleClass extends Component {
  render() {
    if (__DEV__) {
      renderCount += 1;
      console.log(`${this.constructor.name}. renderCount: `, renderCount);
    }
    return (
        <View>
          <Text>bla</Text>
        </View>
    )
  }
}

对于功能组件:

import React from 'react';
import { View, Text } from 'react-native';
let renderCount = 0;

export function SampleFunctional() {
  if (__DEV__) {
    renderCount += 1;
    console.log(`${SampleFunctional.name}. renderCount: `, renderCount);
  }

  return (
    <View>
      <Text>bla</Text>
    </View>
  )
}