【发布时间】:2019-09-21 19:35:22
【问题描述】:
我想知道是否有一种模式可以让我防止 HOC 根据某些条件重新计算,这是一个示例:
const DumbComponent = () => <button>Click me<button/>;
// Third party HOC, that I can't modify
const SmartComponent = Component => class extends Component {
componentWillReceiveProps() {
// Complex stuff that only depends on one or 2 props
this.state.math = doExpensiveMath(props);
}
render() {
return <Component {...this.props} math={this.state.math} />;
}
}
const FinalComponent = SmartComponent(DumbComponent);
我正在寻找的是一种模式,如果我知道它所依赖的道具没有改变,它会阻止这个 HOC 做它的事情。但这并不能阻止整个树基于像 shouldComponentUpdate 这样的 props 进行重新渲染。
问题是,这个 HOC 来自另一个库,理想情况下我不想分叉它。
【问题讨论】:
-
很难不知道
SmartComponent在做什么,但如果它只是计算,那么你应该Memoize传递给它的道具(也许散列道具)值 obj 并直接渲染这种情况下的子组件。