【问题标题】:How to prevent React component mounting if props are empty?如果 props 为空,如何防止 React 组件安装?
【发布时间】:2020-01-21 01:23:53
【问题描述】:

我有一个与第三方库配合使用的组件,我需要在组件安装后添加监听器。出于某种原因,如果没有从服务器异步获取并通过“连接”函数(来自 react-redux)的数据,我无法添加侦听器。 如果 props 为空,如何防止 React 组件挂载?

【问题讨论】:

    标签: reactjs react-redux


    【解决方案1】:

    经过一番研究,我没有找到解决方案,所以我写了我的:

    // No Props No Mount
    import React from 'react';
    import _ from 'lodash';
    
    function NPNM(WrappedComponent) {
      return class extends React.Component {
        render() {
          const { children } = this.props;
          const data = _.omit(this.props, children);
          let hasProps = true;
    
          _.forEach(data, elm => {
            if (_.isEmpty(elm) && !_.isFunction(elm)) hasProps = false;
          });
    
          return hasProps ? <WrappedComponent {...this.props} /> : <></>;
        }
      };
    }
    
    export default NPNM;
    

    应该像这样使用

    connect(mapStateToProps, mapDispatchToProps)(NPNM(YourComponent));
    

    【讨论】:

      猜你喜欢
      • 2021-01-24
      • 2016-01-14
      • 2021-11-05
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      相关资源
      最近更新 更多