仅在使用 HOC 时查询组件中的元素类型错误

Element type error in Query component only when using a HOC

我创建了一个 withInfiniteScroll 高阶组件,用于向简单的数据列表添加无限滚动。我正在尝试在 apollo 的 Query 组件中使用该 HOC。这是我收到元素错误的地方:

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of Query.

我也看到这个错误(不确定那是什么意思...):

Uncaught (in promise) Error: ObservableQuery with this id doesn't exist: 3

当我不使用 HOC 时代码工作正常

<Query>
    {(data) => return <List list={data.list} /> }
</Query>

但是当我添加 HOC 时它坏了...

import withInfiniteScroll from './withInfiniteScroll';

const ListWithInfiniteScroll = withInfiniteScroll(List);

<Query>
    {(data) => return <ListWithInfiniteScroll list={data.list} /> }
</Query>

我很确定我没有混淆 default/named 进口。作为参考,这里是 HOC 实现(简化):

const withInfiniteScroll = (Component) => {
    class WithInfiniteScroll extends React.Component {
        // Stuff here

        render() {
            return <Component {...this.props} />;
        }
    }
}

export default withInfiniteScroll;

尝试将数据传递到列表并在之后包装到 HOC 中,例如

import withInfiniteScroll from './withInfiniteScroll';

const ListWithData = (props) => (
  <Query>
    {(data) => return <List list={data.list} /> }
  </Query>
)

const ListWithInfiniteScroll = withInfiniteScroll(ListWithData);

在您的示例中,您似乎没有 return 在高阶组件函数中创建新的 class。因此,withInfiniteScroll(Component) 将 return 未定义。导致 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

试试这个:

const withInfiniteScroll = (Component) => {
    class WithInfiniteScroll extends React.Component {
        // Stuff here

        render() {
            return <Component {...this.props} />;
        }
    }

    // This line is important!
    return WithInfiniteScroll;
}

export default withInfiniteScroll;

您还可以删除粗箭头函数周围的括号以直接 return class,如下所示:

const withInfiniteScroll = Component => class extends React.Component { ... }