背景
我有一个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})
}发布于 2020-05-27 14:59:23
使用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>
)
}
}发布于 2020-05-27 15:01:59
使用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发布于 2020-05-27 14:57:56
一种快速的解决方案是将输入移动到自己的组件。
更复杂的解决方案是调整DealGraph组件中的shouldComponentUpdate函数,如这里所述的React: Parent component re-renders all children, even those that haven't changed on state change
https://stackoverflow.com/questions/62036973
复制相似问题