开发者社区> 问答> 正文

#React HOC的局限性是什么?

#React HOC的局限性是什么?

展开
收起
因为相信,所以看见。 2020-05-08 11:00:31 601 0
1 条回答
写回答
取消 提交回答
  • 阿里,我所有的向往

    高阶组件除了具有一些优点外,还需要注意一些事项。以下是订单中列出的几个

    不要在render方法内使用 HOC :不建议在组件的render方法内将HOC应用于组件。

    render() {
      // A new version of EnhancedComponent is created on every render
      // EnhancedComponent1 !== EnhancedComponent2
      const EnhancedComponent = enhance(MyComponent);
      // That causes the entire subtree to unmount/remount each time!
      return <EnhancedComponent />;
    }
    
    

    上面的代码通过重新安装导致该组件及其所有子组件的状态丢失的组件来影响性能。相反,应在组件定义之外应用HOC,以使生成的组件仅创建一次 必须复制静态方法: 将HOC应用于组件时,新组件没有原始组件的任何静态方法

    // Define a static method
    WrappedComponent.staticMethod = function() {/*...*/}
    // Now apply a HOC
    const EnhancedComponent = enhance(WrappedComponent);
    
    // The enhanced component has no static method
    typeof EnhancedComponent.staticMethod === 'undefined' // true
    You can overcome this by copying the methods onto the container before returning it
    function enhance(WrappedComponent) {
      class Enhance extends React.Component {/*...*/}
      // Must know exactly which method(s) to copy :(
      Enhance.staticMethod = WrappedComponent.staticMethod;
      return Enhance;
    }
    
    

    引用没有通过: 对于HOC,您需要将所有道具传递到包装的组件,但这对引用不起作用。这是因为ref实际上不是与key相似的道具。在这种情况下,您需要使用React.forwardRef API

    2020-05-08 11:01:46
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
利用编译将 Vue 组件转成 React 组件 立即下载
React Native 全量化实践 立即下载
React在大型后台管理项目中的工程实践 立即下载