HOC与useContext无效的挂接调用挂钩只能在功能组件的主体内部调用

问题描述

我正在尝试使用MaterialUI的Snackbar编写HOC,以便能够在任何网络故障中显示错误。遇到错误,有人可以帮忙吗?

react-dom.development.js:14724未捕获的错误:无效的挂钩调用。挂钩只能在功能组件的主体内部调用。发生这种情况可能是由于以下原因之一:

  1. 您可能使用了不匹配的React和渲染器版本(例如React DOM)
  2. 您可能正在违反挂钩规则
  3. 您可能在同一应用中拥有多个React副本
import React from 'react'
import Snackbar from '@material-ui/core/Snackbar'

const SnackbarContext = React.createContext(null)

const withSnackbar = (OriginalComponent) => {
  function componentWithSnackbarContext() {
    const [state,setState] = React.useState({
      open: false,message: 'Some network error occurred',})

    const { open,message } = state

    const handleNetworkFail = (messageText) => () => {
      setState({ open: true,message: messageText })
    }

    const handleClose = () => {
      setState({ ...state,open: false })
    }

    return (
      <>
        <SnackbarContext.Provider value={{ handleNetworkFail,handleClose }}>
          <OriginalComponent />
        </SnackbarContext.Provider>
        <Snackbar
          anchorOrigin={{ vertical: 'top',horizontal: 'center' }}
          open={open}
          onClose={handleClose}
          message={message}
        />
      </>
    )
  }
  return componentWithSnackbarContext
}

export default withSnackbar

解决方法

lint规则假定以大写字母开头的函数是组件,而以小写字母开头的函数不是组件。解决方法是将componentWithSnackbarContext更改为ComponentWithSnackbarContext

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...