在 React 中导出一个高阶组件



我有一个以下加载组件,它是一个 HOC

import React, { Component } from "react";
const isEmpty = prop =>
prop === null ||
prop === undefined ||
(prop.hasOwnProperty("length") && prop.length === 0) ||
(prop.constructor === Object && Object.keys(prop).length === 0);
const LoadingHOC = loadingProp => WrappedComponent => {
return class LoadingHOC extends Component {
componentDidMount() {
this.startTimer = Date.now();
}
componentWillUpdate(nextProps) {
if (!isEmpty(nextProps[loadingProp])) {
this.endTimer = Date.now();
}
}
render() {
const myProps = {
loadingTime: ((this.endTimer - this.startTimer) / 1000).toFixed(2)
};
return isEmpty(this.props[loadingProp]) ? (
<div className="loader" />
) : (
<WrappedComponent {...this.props} {...myProps} />
);
}
};
};
export default LoadingHOC;

我在Feed组件中使用它来产生加载效果。

饲料成分为:

import React, { Component } from "react";
import FeedItem from "./FeedItem";
import LoadingHOC from "./HOC/LoadingHOC";
class Feed extends Component {
state = {
filterText: ""
};
render() {
const { loadingTime } = this.props;
return (
<div className="feed">
<FeedItem
contacts={this.props.contacts}
filterText={this.state.filterText}
/>
{/* <p>Loading time {loadingTime} seconds</p> */}
</div>
);
}
}
export default LoadingHOC("contacts", Feed);

我正在App.js中使用Feed组件,就像<Feed contacts={this.state.contacts} />这样。

但是我收到以下错误 -Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

我知道这是因为 HOC 没有被正确调用。但是我在export default LoadingHOC("contacts", Feed);做错了什么?

你的 HOC 是一个柯里函数。所以你需要打电话两次

export default LoadingHOC("contacts")(Feed);

相关内容

最新更新