反应-防止HOC基于props重新计算

时间:2019-05-03 09:13:07

标签: reactjs recompose

我想知道是否有一种模式可以防止基于某些条件重新计算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这样的道具进行重新渲染。

要注意的是,此HOC来自另一个库,理想情况下,我不想派发它。

1 个答案:

答案 0 :(得分:0)

我得到的是您想防止临时重新计算某些逻辑,因此您可以按照以下步骤进行操作:-

const DumbComponent = () => <button>Click me<button/>;

// Third party HOC
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 withHoc = SmartComponent(DumbComponent);
class FinalComponent extends Component { 
    render() {
        if (your condition here) { 
            return (
                <withHoc {...this.props} />
            ); 
        }

        else {
            return <DumbComponent {...this.props}/>;
        }
    }
}

export default FinalComponent;