React High Order Components Error: Element type is invalid: expected a string or a class/function but got: object

React High Order Components Error: Element type is invalid: expected a string or a class/function but got: object

我在 React 17.0.2 中尝试实现高阶组件 (HOC) 时遇到此错误:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

我在线搜索了该错误,但找不到任何关于可能产生该错误的指南。这是重现错误的简化代码: index.js

import React from 'react'
import ReactDOM from 'react-dom'

import './index.css'

import App from './components/App'

ReactDOM.render(<App />, document.getElementById('root'))

index.css

body { background-color: aquamarine; }

withPointlessHOC.js

import React from 'react'

export default function withPointlessHOC(component) {
    const Component = component
    return (
        <div>
            <Component />
        </div>
    )
}

App.js

import React from 'react'

import withPointlessHOC from './withPointlessHOC'

function App() {
    return (
        <div>
            Hello
        </div>
    )
}

const PointlessHOC = withPointlessHOC(App)
export default PointlessHOC

问题是我忘记了 return 一个函数并试图正常渲染。在 HOC 中,你必须 return 一个包含渲染指令的函数。一旦我通过将 return 添加到 withPointlessHOC 中来更正此问题,如下所示:

从 'react'

导入 React

// 高阶组件或 HOC 是一个将组件作为其第一个参数的函数,return 是一个包装给定组件的新组件,为其提供额外的功能。

export default function withPointlessHOC(component) {
    const Component = component
    return function(props) {
        return (
            <div>
                <Component />
            </div>
        )
    }
    
}

瞧,错误消失了。为了使它完整(毫无意义,除了理解错误),我将道具散布在 using:

import React from 'react'

export default function withPointlessHOC(component) {
    const Component = component
    return function(props) {
        return (
            <div>
                <Component {...props}/>
            </div>
        )
    }
    
}