You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中withLoadingIndicator高阶组件实现是否正确?请排查问题

高阶组件withLoadingIndicator运行异常排查

你的代码核心逻辑是正确的,但运行异常大概率是以下几个遗漏点导致:

1. 未导入React

在React 17版本之前,所有使用JSX的文件必须显式导入React,否则编译时会抛出React is not defined错误。你需要在文件顶部添加:

import React from 'react';

2. 缺失组件displayName(非运行错误,但影响调试)

HOC返回的组件默认没有自定义displayName,会导致React DevTools里显示为WithLoadingIndicator,无法区分是包裹了哪个组件的HOC。建议为返回的组件添加displayName,方便调试:

function withLoadingIndicator(Component) {
  function WithLoadingIndicator(props) {
    if (props.isLoading) {
      return <div>Loading...</div>;
    }
    return <Component {...props} />;
  }
  // 添加displayName
  WithLoadingIndicator.displayName = `WithLoadingIndicator(${Component.displayName || Component.name || 'Component'})`;
  return WithLoadingIndicator;
}

3. 未处理isLoading未传递的场景(潜在问题)

如果父组件没有传递isLoading属性,props.isLoading会是undefined,此时会直接渲染MyComponent。如果此时data也未准备好,MyComponent会显示空内容。你可以添加默认props来避免这种情况:

function WithLoadingIndicator(props) {
  const { isLoading = false, ...restProps } = props;
  if (isLoading) {
    return <div>Loading...</div>;
  }
  return <Component {...restProps} />;
}

修正后的完整代码示例

import React from 'react';

function withLoadingIndicator(Component) {
  function WithLoadingIndicator(props) {
    const { isLoading = false, ...restProps } = props;
    if (isLoading) {
      return <div>Loading...</div>;
    }
    return <Component {...restProps} />;
  }
  
  WithLoadingIndicator.displayName = `WithLoadingIndicator(${Component.displayName || Component.name || 'Component'})`;
  return WithLoadingIndicator;
}

class MyComponent extends React.Component {
  render() {
    return <div>{this.props.data}</div>;
  }
}

const MyComponentWithLoadingIndicator = withLoadingIndicator(MyComponent);

export default MyComponentWithLoadingIndicator;

内容的提问来源于stack exchange,提问作者SAM PANIAGUA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:40:37