避免在更改状态变量时更新组件

Avoid component update while changing state vaiable

背景

我有一个 React 组件,其中包含另外两个组件。 I 组件包括一个图表(使用 react-charts 构建),另一个是一个简单的输入字段。我最初不可见但是当有人点击那里的图标时它变得可见。

问题,子项在状态更改时重新呈现

现在的问题是,每当我切换此输入字段时,它都会自动刷新我的图表。事实上,当我在我的输入字段中输入时,它也会刷新图表。我认为它会在我更新状态变量时重新渲染图形。我想停止这种行为。关于如何执行此操作的任何建议。

组件截图(https://i.imgur.com/zeCQ6FC.png)

组件代码

<div className="row">
  <DealGraph ref={this.dealRef} />
  <div className="col-md-4">
    <div className="row">
      <div style={style} className="col-md-12 bg-white border-radius-10  default-shadow">
        <h3 className="sub-heading roboto" style={border}>
          Create Deals
        </h3>
        <input
          type="text"
          name="deal"
          className="form-control mgt-30"
          value="Deal One"
          readOnly
        />
        <button
          type="button"
          onClick={this.showAddBlock}
          style={button}
          className="golden-button create-deal-button"
        >
          <i className="fa fa-plus"></i>
        </button>
        {addDealStatus ? (
          <div className="col-md-12 add-deal-box pd-0-0">
            <input
              type="text"
              className="form-control mgt-30 mgb-10"
              name="add-deals"
              placeholder="Add Deals"
            />
            <button type="button" className="golden-button flex all-center">
              Add
            </button>
          </div>
        ) : null}
      </div>
    </div>
  </div>
</div>

切换功能

showAddBlock=() => {
  this.setState({addDealStatus:!this.state.addDealStatus})
}

一个快速的解决方案是将输入移动到自己的组件。

一个更复杂的解决方案是调整 DealGraph 组件中的 shouldComponentUpdate 函数,如此处所述

使用 PureComponent

要阻止子组件从其父组件重新呈现,您应该将子组件设为纯组件。

import React from 'react';

class DealGraph extends React.PureComponent { // notice PureComponent

  render() {
    const { label, score = 0, total = Math.max(1, score) } = this.props;

    return (
      <div>
        /* Your graph code */
      </div>
    )
  }

}

使用来自 Recompose 的 { pure } HOC

您可以使用包装在来自 recompose 的纯 HOC 中的功能组件

import React from 'react';
import { pure } from 'recompose';

function DealGraph(props) {
  return (
    <div>
      /* Your graph code */
    </div>
  )
}

export default pure(DealGraph); // notice pure HOC

默认情况下,在渲染每个组件时都会检查 shouldComponentUpdate。React 组件不会通过 default.So 实现 shouldComponentUpdate,或者我们可以实现 shouldComponentUpdate。或将 child class 作为纯成分。