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
相关产品推荐
相关产品推荐

