【发布时间】:2020-03-08 23:58:27
【问题描述】:
更新后,React 不再使用高阶组件 (HOC) 中的 useEffect 钩子编译代码。我有一个 HOC,它连接到 Redux 存储并在需要时分派一个操作来获取数据。
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
【问题讨论】:
标签: reactjs redux higher-order-components