在更高阶组件中调用useEffect

时间:2019-11-13 08:16:45

标签: reactjs redux higher-order-components

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

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

1 个答案:

答案 0 :(得分:2)

您的组件名称必须以大写字母开头,这就是为什么出现此问题的原因。您还可以优化connect和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