[英]HOC with useContext. Invalid hook call. Hooks can only be called inside of the body of a function component
I am trying to write an HOC with MaterialUI's Snackbar to be able to show error in any.network failure.我正在尝试使用 MaterialUI 的 Snackbar 编写一个 HOC,以便能够在任何网络故障中显示错误。 Getting below error, can someone please help:
出现以下错误,有人可以帮忙:
react-dom.development.js:14724 Uncaught Error: Invalid hook call. react-dom.development.js:14724 未捕获错误:无效的挂钩调用。 Hooks can only be called inside of the body of a function component.
钩子只能在 function 组件的内部调用。 This could happen for one of the following reasons:
这可能由于以下原因之一而发生:
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
The lint rule assumes that functions starting with capital letters are components, and ones with lower case letters are not. lint 规则假定以大写字母开头的函数是组件,而以小写字母开头的函数不是。 The fix is to change
componentWithSnackbarContext
to ComponentWithSnackbarContext
解决方法是将
componentWithSnackbarContext
更改为ComponentWithSnackbarContext
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.