首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >避免在更改状态时更新组件

避免在更改状态时更新组件
EN

Stack Overflow用户
提问于 2020-05-27 14:44:27
回答 4查看 126关注 0票数 1

背景

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

问题,子对象在状态更改时呈现

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

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

组件代码

代码语言:javascript
复制
<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>

切换功能

代码语言:javascript
复制
showAddBlock=() => {
  this.setState({addDealStatus:!this.state.addDealStatus})
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2020-05-27 14:59:23

使用PureComponent

要停止从子组件的父组件重新渲染,您应该使子组件成为纯组件。

代码语言:javascript
复制
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>
    )
  }

}
票数 1
EN

Stack Overflow用户

发布于 2020-05-27 15:01:59

使用Recompose中的{ pure } HOC

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

代码语言:javascript
复制
import React from 'react';
import { pure } from 'recompose';

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

export default pure(DealGraph); // notice pure HOC
票数 0
EN

Stack Overflow用户

发布于 2020-05-27 14:57:56

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

更复杂的解决方案是调整DealGraph组件中的shouldComponentUpdate函数,如这里所述的React: Parent component re-renders all children, even those that haven't changed on state change

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62036973

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档