gpt4 book ai didi

reactjs - useEffect 在高阶组件中调用

转载 作者:行者123 更新时间:2023-12-04 11:00:29 24 4
gpt4 key购买 nike

更新后,React 不再编译带有 useEffect 的代码高阶组件(HOC)中的钩子(Hook)。我有一个 HOC,它连接到 Redux 存储并在需要时分派(dispatch)一个操作来获取数据。

import React, {useEffect} from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'

import SpinCenter from '../components/SpinCenter'
import { fetchObject } from '../actions/objects'
import { fetchIfNeeded } from '../utils'


const withObject = ({element}) => WrappedComponent => ({id, ...rest}) => {
const hoc = ({status, object, fetchObject}) => {
useEffect(() => {
fetchIfNeeded(
status,
()=>fetchObject(element, id),
)
})

// Initial loading and error
if (status === undefined || object === undefined) return <SpinCenter/>
if (status.error) return <>error loading: {status.error.message}</>

// Pass through the id for immediate access
return <WrappedComponent {...{object, status, id}} {...rest} />
}

hoc.propTypes = {
object: PropTypes.object,
status: PropTypes.object,
fetchObject: PropTypes.func.isRequired,
}

const mapStateToProps = state => ({
object: state.data[element][id],
status: state.objects[element][id]
})

const mapDispatchToProps = {
fetchObject
}

const WithConnect = connect(mapStateToProps, mapDispatchToProps)(hoc)
return <WithConnect/>
}

export default withObject

我希望这是有道理的。我想最好的方法是以某种方式放置 useEffect进入一个功能组件,但是这一切应该发生的地方变得有点复杂。谁能帮我理解这一点?

这是我得到的错误。
React Hook "useEffect" is called in function "hoc" which is neither a React function component or a custom React Hook function

最佳答案

您的组件名称需要以大写字符开头,这就是您遇到此问题的原因。您还可以优化连接和 hoc 代码以返回一个 hoc 实例,而不是一次又一次地执行它

const withObject = ({element}) => WrappedComponent => {
const Hoc = ({id, status, object, fetchObject,...rest}) => {
useEffect(() => {
fetchIfNeeded(
status,
()=>fetchObject(element, id),
)
})

// Initial loading and error
if (status === undefined || object === undefined) return <SpinCenter/>
if (status.error) return <>error loading: {status.error.message}</>

// Pass through the id for immediate access
return <WrappedComponent {...{object, status, id}} {...rest} />
}

Hoc.propTypes = {
object: PropTypes.object,
status: PropTypes.object,
fetchObject: PropTypes.func.isRequired,
}

const mapStateToProps = state => ({
object: state.data[element][id],
status: state.objects[element][id]
})

const mapDispatchToProps = {
fetchObject
}

return connect(mapStateToProps, mapDispatchToProps)(Hoc)
}

export default withObject

关于reactjs - useEffect 在高阶组件中调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58832843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com