【问题标题】:React High Order Components Error: Element type is invalid: expected a string or a class/function but got: object反应高阶组件错误:元素类型无效:期望字符串或类/函数但得到:对象
【发布时间】:2021-10-24 21:32:36
【问题描述】:

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

错误:元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件),但得到:对象。

我在网上搜索了该错误,但找不到任何关于可能导致该错误的指导。这是重现错误的简化代码: 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

【问题讨论】:

    标签: javascript reactjs compiler-errors components


    【解决方案1】:

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

    从“反应”导入反应

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

    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>
            )
        }
        
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-03
      • 2020-03-11
      • 2019-09-06
      • 2018-02-19
      • 2020-07-18
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 2017-11-02
      相关资源
      最近更新 更多