编写我的第一个 HOF 反应组件时出错:如果您返回返回组件而不是<组件 />,则可能会发生这种情况



我正在编写一个非常简单的react组件,但我尝试的所有操作都会出现控制台错误。

在我的主要渲染中:


render() {
const subreddits = withFetch(new Subreddits({}));
...
{subreddits}
}

子区域:

class Subreddits extends React.Component<Record<string, unknown>, any> {
displayName: string;
constructor(props: any) {
super(props);
this.displayName = "Subreddits";
}
public render() {
const data = this.props.data?.[0];
const options = data?.map((e) => ({
name: e,
value: e,
}));
return (
<SelectSearch
search={true}
options={options}
value={this.props.input.h}
name="reddit select"
placeholder="Select"
onChange={async (handle: string) => {
}}
/>
);
}
}

我将fetch修改为更简单:

function withFetch(WrappedComponent) {
return class extends React.Component {
displayName: string;
constructor(props) {
super(props);
this.displayName = "log";
}
componentDidMount() {
console.log("Hello World!");
}
render() {
return <WrappedComponent />;
}
};
}
export default withFetch;

请原谅目前打字不好。这是我得到的错误:

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.
in div (created by InputGroup)
in InputGroup (created by App)
in div (created by App)
in div (created by App)
in App (created by HotExportedApp)
in AppContainer (created by HotExportedApp)
in HotExportedApp

好吧,我意识到它不能呈现函数,但我打开调试器,它不是函数,而是对象。我试着像函数一样调用它,只是为了确定,但事实并非如此。这就留下了另一个选项if you return a Component instead of <Component />。然而,对我来说,这似乎很好。当我注释掉{subreddits}时,错误就会消失。我犯了什么错误?

高阶组件的参数是要包装的组件的类(或函数(,而不是该组件的实例。

您要做的是通过将HOC应用于包装/内部组件来创建一个新组件。这应该在render((之外发生,因为它应该只发生一次,而不是每次重新渲染时。

const FetchableSubreddits = withFetch(Subreddits);

然后在渲染中,您可以像使用任何其他JSX组件一样使用它。

<FetchableSubreddits someProp={someValue} />

最新更新