如果道具为空,如何防止React组件安装?

问题描述 投票:1回答:1

我有一个与第三方库一起使用的组件,在组件安装后,我需要添加侦听器。由于某种原因,我无法添加没有从服务器异步获取并通过“ connect”功能(来自react-redux)传递的数据的侦听器。如果道具为空,如何防止React组件安装?

reactjs react-redux
1个回答
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));
© www.soinside.com 2019 - 2024. All rights reserved.