【问题标题】:React - prevent HOC from recomputing based on propsReact - 防止 HOC 基于 props 重新计算
【发布时间】: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 并直接渲染这种情况下的子组件。

标签: reactjs recompose


【解决方案1】:

我得到的是你想防止 hoc 重新计算某些逻辑,你可以这样做:-

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; 

【讨论】:

    猜你喜欢
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 2018-05-16
    • 2012-11-14
    相关资源
    最近更新 更多